显式具体化,显式实例化

 1 template <class T>
 2 class A
 3 {
 4     T *t;
 5     
 6 public:
 7     A()
 8     {
 9         t = new T();
10     }
11 };
12 
13 template class A<int>;
14 
15 template<> class A<double>
16 {
17     double d;
18 public:
19     A()
20     {
21         d = 0.0;
22     }
23 };

上面第13行叫做显式实例化。如果这样使用模板 A<char> c 编译器会自动推到c的类型,这叫隐式实例化。
显示实例化相当于告诉编译器先定义这么一个类型(上面的A<int>),即使还没有使用它。
显示实例化在模板类的.h文件与.cpp文件分离时有用。

而上面15~23行叫做显式具体化,或者叫做模板特化
这个用来对某种T做特殊处理,例如std::string。

参考:http://blog.sina.com.cn/s/blog_62b1508e0100hl8a.html
     https://blog.csdn.net/u012750314/article/details/52770847
    

posted @ 2018-06-22 18:55  Droplet  阅读(454)  评论(0编辑  收藏  举报