在命名空间内的lambda中使用时未找到运算符重载

时间:2018-04-06 09:12:46

标签: c++ operator-overloading using

以下内容无法编译(使用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;
  };
}

2 个答案:

答案 0 :(得分:4)

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

  

对于非限定名称,即不在范围解析运算符::右侧显示的名称,名称查找检查范围如下所述,直到它找到至少一个任何类型的声明,此时查找停止,不再检查其他范围。

请注意这两个示例的工作原理。只显示更改的段,其余代码仍然可见,以便编译。

在非限定名称查找中明确包含:: 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

答案 1 :(得分:3)

这是因为ADL不会自动搜索封闭的命名空间,除非它是内联命名空间:

cppreference

  

如果关联的类和名称空间集合中的任何名称空间是内联名称空间,则其封闭名称空间也会添加到集合中。

请考虑以下代码:

namespace N {
    namespace M {
        struct foo {};
    }

    void operator+(M::foo, M::foo) {}
}


int main()
{
    N::M::foo f;
    f + f; // Error, enclosing namespace N won't be searched.
}

同样,在您的情况下,关联的命名空间为std,ADL不会考虑封闭的全局命名空间。

实际上,代码中的operator+是通过非限定名称查找找到的,只要找到名称就会停止。在operator+中声明namespace ns时,首先找到此运算符,并且不会搜索全局名称空间中的运算符。