【发布时间】:2014-10-08 00:57:02
【问题描述】:
考虑这段代码:
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
如何解决这个问题?当该运算符 可能 对两个不同的实例具有相同的签名时,如何在模板中拥有一个朋友运算符?如何在不触发重定义错误的情况下解决这个问题?
【问题讨论】:
-
在
operator<<的定义中需要T吗? -
int 已经可以与
operator<<一起使用。由每个班级提供合适的operator<< -
我真的不明白你为什么要为 K 实现
operator<<,尤其是为什么你需要它与(几乎)不相关的类A<T,K>成为朋友。正如 Neil 所说,由K提供运算符的实现,而int已经有了。 -
你没有。您在类中定义与类相关的操作,而不是其模板化参数。
-
我同意 CashCow 的观点。在您的示例中,流插入器实际上不需要成为
struct A的朋友。它可能需要成为K的朋友,但它不需要了解A的内部结构。
标签: c++ templates c++11 operator-overloading