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 expressions ( std::vector<double, std::allocator<double> >and std::vector<double, std::allocator<double>>)
#include <functional>
#include <vector>
namespace ns{
using MyType = std::vector<double>;
}
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();
return y;
};
}
}
The compiler does not find the correct overload operator+. I do not understand why. The reason I define operators outside of the namespace is because ADL does not work for typedefs and uses type aliases . What is the problem? Why can't the compiler find operator+(MyType, const MyType &)in the above circumstances?
All of the following options are compiled:
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;
};
}
source
share