The following does not compile (with Clang 5.0.0 / gcc 7.3, std: C++11):
Error message in Clang:
error: invalid operands to binary expression (std::vector<double, std::allocator<double> > and std::vector<double, std::allocator<double>>)
#include <functional>
#include <vector>
namespace ns{
using MyType = std::vector<double>;
} // namespace ns
using ns::MyType;
MyType& operator+=( MyType& lhs, const MyType& rhs) {
for (int i = 0; i < lhs.size(); ++i) {
lhs[i] = lhs[i] + rhs[i];
}
return lhs;
}
MyType operator+( MyType lhs, const MyType& rhs) {
lhs += rhs;
return lhs;
}
namespace ns{
using Func = std::function<MyType()>;
Func operator+(
const Func &lhs, const Func &rhs) {
return [lhs, rhs]() {
auto y = lhs() + rhs(); // <-- error in this line
return y;
};
}
} // namespace ns
The compiler does not find the correct overload of operator+. I do not understand why. The reason I define the operators outside the namespace is that ADL does not work for typedefs and using type aliases. What is the problem here? Why can't the compiler find operator+(MyType, const MyType &) in the above circumstances?
All of the following alternatives do compile:
namespace ns {
MyType a, b;
auto c = a + b; // compiles
MyType f() {
MyType a_, b_;
return a_ + b_; // compiles
};
Func operator+(
const Func &lhs, const Func &rhs) {
return [lhs, rhs]() {
auto x = lhs();
x += rhs(); // <-- compiles; operator+= instead of operator+
return x;
};
}
} // namespace ns
Func operator+(
const Func &lhs, const Func &rhs) {
return [lhs, rhs]() {
auto y = lhs() + rhs(); // <-- no error if not in namespace ns
return y;
};
}
operator+I want to use is forMyType, which is the result of calling an instance of Func. The code islhs() + rhs(), notlhs + rhs. Am I missing something here?operator+(MyType, const MyType &)in the above circumstances? I updated the question to clarify this more.