c++ - 模板结构中的友元运算符引发重新定义错误

标签 c++ templates c++11 operator-overloading

考虑这段代码:

template<typename T,typename K>
struct A{

   friend std::ostream& operator<<(std::ostream& out, K x) { 
      // Do some output 
      return out; 
   }

};

int main(){
   A<int,int> i;
   A<double,int> j;
}

它不编译,因为 A 的两个实例实例化了 operator<<两次使用相同的签名,所以我收到此错误:

test.cpp:26:25: error: redefinition of ‘std::ostream& operator<<(std::ostream&, int)’
    friend std::ostream& operator<<(std::ostream& out, K x) { return out; }
                         ^
test.cpp:26:25: error: ‘std::ostream& operator<<(std::ostream&, int)’ previously defined here

如何解决这个问题?当该运算符可能对两个不同的实例化具有相同的签名时,我如何才能在模板中拥有一个友元运算符?如何在不触发重新定义错误的情况下解决此问题?

最佳答案

我真的看不出像这样声明 friend 有什么用,尽管如此你可以这样做:

template<typename T, typename K>
struct A{
  template<typename L>
  friend std::ostream& operator<<(std::ostream& out, L const &x);
};

template<typename T>
std::ostream& operator<<(std::ostream& out, T const &x) {
  // ... 
  return out;
}

LIVE DEMO

编辑:

另一个可能更接近您想要的选项是:

template<typename T>
std::ostream& operator<<(std::ostream& out, T const &x);

template<typename T, typename K>
struct A{
  friend std::ostream& operator<<<K>(std::ostream& out, K const &x);
};

template<typename T>
std::ostream& operator<<(std::ostream& out, T const &x) { 
  // ...
  return out;
}

LIVE DEMO

但真的不确定你为什么要这个。恕我直言,您的设计存在严重缺陷。

关于c++ - 模板结构中的友元运算符引发重新定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306944/

相关文章:

c++ - 函数返回值的可变性测试

c++ - 尝试使 C++ (MFC) 代码片段易于重用。有什么选择?

c++ - 自动扣除别名模板和模板类的模板参数

c++ - C++11 的按值传递/常量正确性

c++ - 处理可能不指向任何东西的指针

c++ - 无法使方法存在检测机制起作用

c++ - 为什么我无法构建此正则表达式

c++ - 使用 Cereal 库序列化 Eigen::Matrix

c++ - 使用 MPFR 时如何在 Boost Multi precision 中设置舍入模式

用于类型和非类型模板的 c++ auto