本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti… 本文是在海贼班学习的一些笔记。 下面定义了一个模板类PRINT。注意:
- PRINT是模板,PRINT才是类的名字。我们必须将PRINT 实例化成123后才能调用print(123)。
- 我们可以看出print是被定义成了PRINT。我们不能执行print<"hello">或print_int<"hello">来打印字符串。
- PRINT(789)是生成一个PRINT类的对象,而不是调用operator()。而且我们还必须定义相应构造函数才行。
#include using namespace std;
template class PRINT { public : PRINT &operator()(T a) { cout << a << endl; return *this; } };
int main() { PRINT print; //跟模板函数不一样,这里必须声明类型 print(123); print(456); //PRINT(789); //出错 PRINT print_int; print_int(123); print_int(456); //print("fwgew"); //出错 PRINT print_string; print_string("hello world"); print_string("haizei");
return 0;
} 采用下面的添加了转换构造函数和缺省构造函数后上面的PRINT(789)就可以通过编译了。不过它只是生成一个PRINT类的实例而已。
template class PRINT { public : PRINT() {} PRINT(int a) {}; PRINT &operator()(T a) { cout << a << endl; return *this; } };
上面的方法有点繁琐,因为还得根据不同的类型来实例化不同的print函数(print_int, print_string)。那么有没有以不变应万变的方法呢?有的。
答案就是把template这一行移到到operator()函数的上方即可。我们可以看出这个类的T实际上只对operator()起作用了。个人觉得,那么这个PRINT好像就不算模板类了,只是普通类里面包了一个模板函数而已。
#include using namespace std;
//template class PRINT { public : //PRINT() {} //PRINT(int a) {}; template PRINT &operator()(T a) { cout << a << endl; return *this; } };
int main() { PRINT print; print(123); print("hello world!"); print("123")("hello world!")("hello haizei"); return 0; } 结果是
123 hello world! 123 hello world! hello haizei
———————————————— 版权声明:本文为CSDN博主「纸上得来终觉浅 绝知此事要躬行」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。