【发布时间】:2018-04-06 09:12:46
【问题描述】:
以下内容无法编译(使用 Clang 5.0.0 / gcc 7.3,std: C++11):
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 does not work for typedefs and using type aliases。这里有什么问题?为什么在上述情况下编译器找不到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;
};
}
【问题讨论】:
-
@user463035818 我要使用的
operator+是MyType,是调用Func实例的结果。代码是lhs() + rhs(),而不是lhs + rhs。我在这里错过了什么吗? -
呃,对不起,我错过了一些东西。请在问题中包含错误消息
-
@JiveDadson 是的:“这里有什么问题?”,意思是为什么这不能编译?为什么在上述情况下编译器找不到
operator+(MyType, const MyType &)?我更新了问题以进一步澄清这一点。 -
这里有一个有趣的花絮:This 编译,但 adding an unrelated operator+ 杀死它...
-
@JiveDadson 他显然想知道是什么使它非法。而且我认为示例大小没有问题,对于他分享的所有观察结果来说,它是完整的、可验证的和最小的。
标签: c++ operator-overloading using