考虑这段代码:
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;
}
编辑:
另一个可能更接近您想要的选项是:
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;
}
但真的不确定你为什么要这个。恕我直言,您的设计存在严重缺陷。
关于c++ - 模板结构中的友元运算符引发重新定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306944/