对于模板下的类定义,一般重载operator<<()用来输出类内部的信息:
我们习惯性写法:
template<typename T>
class A
{
public:
A(string value): data(value){}
friend ostream& operator<< (ostream & out, const A<T>& me);
private:
T data;
};
template<typename T>
ostream& operator<< (ostream & out, const A<T>& me)
{
cout << me.data << endl;
return out;
}
GCC编译器警告:
TemplateFriendFunction.cpp:14: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, const A<T>&)’ declares a non-template function
TemplateFriendFunction.cpp:14: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
出现问题的原因:定义的友元函数还是一个模版,要实例化为参数变元后才能使用
解决方法有两种:(1)把友元函数体放到类声明内部,使其跟着类的实例化一同实例化:
template<typename T>
class A
{
public:
A(string value): data(value){}
friend ostream& operator<< (ostream & out, const A<T>& me)
{
cout << me.data << endl;
return out;
}
private:
T data;
};
方法(2)把友元模版放到类模版声明之上,同样在类模版参数化时附带把友元函数参数化:
template<typename T>
class A
{
public:
A(string value): data(value){}
friend ostream& operator<< <>(ostream & out, const A<T>& me);
private:
T data;
};
template<typename T>
ostream& operator<< (ostream & out, const A<T>& me)
{
cout << me.data << endl;
return out;
}
注意在函数名后加上<>