【发布时间】:2016-03-15 20:51:33
【问题描述】:
以下非模板代码works well:
struct A { };
struct B
{
B() {}
B(const A&) {}
friend B operator+(const B&) { return B(); }
};
B operator+(const B&);
int main()
{
A a;
B b;
+b;
+a;
}
但如果我在这段代码中创建类模板:
template <class T>
struct A { };
template <class T>
struct B
{
B() {}
B(const A<T>&) {}
friend B operator+(const B&) { return B(); }
};
template <class T>
B<T> operator+(const B<T>&); // not really what I want
int main()
{
A<int> a;
B<int> b;
+b;
+a;
}
错误:'operator+' 不匹配(操作数类型为'A
')
是否可以在类外为模板类声明非模板友元函数(就像我在上面为非模板类所做的那样)?
我可以通过为A<T> 参数添加template operator 并在里面调用朋友函数来解决问题,但这并不有趣。
UPD:
另一个解决方法(受R Sahu's answer 启发)是为A 类添加friend 声明:
template <class T>
struct A {
friend B<T> operator+(const B<T>&);
};
但是这个gives a warning,我不知道如何正确修复它。
【问题讨论】:
-
我不确定你想要什么。 B这里是一个模板,所以需要一个模板参数来对其进行操作。如果不是动态确定的模板参数应该是什么?
-
@IceFire
dynamically是什么意思?
标签: c++ templates friend-function