gpt4 book ai didi

c++ - 在 namespace 内的 lambda 中使用时找不到运算符重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:36 25 4
gpt4 key购买 nike

以下不编译(使用 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;
};
}

最佳答案

您正在隐藏全局命名空间 operator+,因为您在当前范围内定义了一个 operator+。非限定名称查找一直移动到封闭的 namespace ,直到找到至少一个声明。因此,因为在当前命名空间中有一个 operator+,无论其参数列表如何,名称查找都不会继续在全局命名空间中进行搜索。参见 here有关合格查找的详细说明。相关位在顶部。

For an unqualified name, that is a name that does not appear to the right of a scope resolution operator ::, name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

请注意这两个示例的工作原理。仅显示更改的段,其余代码必须仍然可见才能编译。

在非限定名称查找中显式包含::operator++

namespace ns {
using Func = std::function<MyType()>;
using ::operator+;

Func operator+(
const Func &lhs, const Func &rhs) {
return [lhs, rhs]() {
auto y = lhs() + rhs();
return y;
};
}

} // namespace ns

确保没有函数隐藏全局 operator+

namespace ns {
using Func = std::function<MyType()>;

Func func(
const Func &lhs, const Func &rhs) {
return [lhs, rhs]() {
auto y = lhs() + rhs();
return y;
};
}

} // namespace ns

关于c++ - 在 namespace 内的 lambda 中使用时找不到运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com