16.6 模板特化

1. 函数特化

template<typename Type>
void template_fun(const Type& t) {
	std::cout << "template_fun" << std::endl;
	std::cout << t << std::endl;
}
/* 函数特化,
 *注意:1.所有特化(包括2、3、4)必须出现在对该模板实例的调用之前,
 *	 2. 优先选择特化实例,当不匹配时,才选择模板
 */
template<> 
void template_fun(const int& num) {
	std::cout << "specialized template_fun" << std::endl;
	std::cout << num << std::endl;
}

2. 类模板特化

template<typename Type>
class Something {
public:
       Something(Type t) :val(t) {}
       Type val;
       void print(const Type& t);
};
template<typename Type> void Something<Type>::print() {
       std::cout << val << std::endl;
}
//类模板特化
template<>
class Something<int> {
public:
      Something(int i) :val(i) {}
      int val;
      // 类模版应该与它特化的模板定义相同的接口
      int otherStuff; // available,but inappropriate
      void print(int i);
};
// 类外定义函数时无需添加 "template<>"
void Something<int>::print() { 
     std::cout << "specialized class " << val << std::endl;
}


3. 特化类成员,而不特化类

template<typename Type>
class Something {
public:
	Something(Type t) :val(t) {}
	Type val;
	void print();
};
// 特化成员而不特化类,注意这里与2中print的不同
template<> 
void Something<char>::print() {
	std::cout << "part specialization!" << val << std::endl;
}
template<typename Type> void Something<Type>::print() {
		std::cout << val << std::endl;
}

4. 类模板的部分特化

template<typename T1, typename T2>
class Something {
};

//部分特化,优先选择
template<typename T1, int>
class Something {
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值