以下代码在 Clang 5.0.0 / gcc 7.3 中无法编译(标准:C++11):
Clang 的错误信息:
错误:二进制表达式的操作数无效(
编译器无法找到正确的
以下所有替代方案都可以编译:
Clang 的错误信息:
错误:二进制表达式的操作数无效(
std::vector<double, std::allocator<double> >
和 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
编译器无法找到正确的
operator+
重载。我不明白为什么。我在命名空间外定义运算符的原因是ADL对于typedef和使用类型别名无法起作用。这里的问题是什么?为什么编译器不能在上述情况下找到 operator+(MyType, const MyType &)
?以下所有替代方案都可以编译:
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+
是针对MyType
的,它是调用Func实例的结果。代码应该是lhs() + rhs()
,而不是lhs + rhs
。我有什么遗漏吗? - user2296653operator+(MyType, const MyType &)
?我更新了问题以更清楚地阐明这一点。 - user2296653