C++友元运算符重载函数的泛型模板写法
2019-03-19 本文已影响0人
youxiaochen
相信很多人都碰到友元运算符重载函数的泛型模板编译不通过的情况
template <typename T>
class Demo
{
//友元运算符重载函数的泛型模板写法
friend Demo operator>> <T> (const Demo &obj, T t);
public:
Demo(T t) {
this->t = t;
}
private:
T t;
public:
T getT() {
return this->t;
}
};
//对应友元运算符重载函数的泛型模板写法
template <typename T>
Demo<T> operator>>(const Demo<T> &obj, T t) {
Demo<T> temp(obj.t + t);
return temp;
}
int main() {
Demo<int> d(4);
Demo<int> d2 = d >> 1;
cout << d2.getT() << endl;
return 0;
}
因为编译器并不是把函数模板处理成能够处理任意类的函数;编译器从函数模板通过具体类型产生不同的函数;编译器会对函数模板进行两次编译:在声明的地方对模板代码本身进行编译,在调用的地方对参数替换后的代码进行编译。
//友元运算符重载函数的泛型模板写法
friend Demo operator>> <T> (const Demo &obj, T t);
//对应友元运算符重载函数的泛型模板写法
template <typename T>
Demo<T> operator>>(const Demo<T> &obj, T t) {
Demo<T> temp(obj.t + t);
return temp;
}