铛。嵌套模板的二元运算符重载

clang. binary operator overloading for nested templates

我正在尝试使用 clang 为嵌套模板 class 重载二元运算符 +,但出现错误 invalid operands to binary expression. Note: candidate template ignored: couldn't infer template argument T。类似于:

template<typename T>
class Container
{
  struct Iterator {
    template<typename U>
    friend typename Container<U>::Iterator operator+(size_t, typename Container<U>::Iterator const&);
   };
};

template<typename U>
typename Container<U>::Iterator
operator+(size_t, typename Container<U>::Iterator const&)
{
  return Container<U>::Iterator{};
}

有没有办法使用 clang 编译器为嵌套模板 class 重载二元运算符?

可以使用C++17

不要将内部函数设为模板。只需将其设为非模板非成员 friend 并将其定义为内联:

template<typename T>
class Container
{
  struct Iterator {
    friend Iterator operator+(size_t, Iterator const&) {
      return {};
    } 
  };
};

这适用于 C++11。 C++03 如果你在 return 中没有 {}