C++ - 类模板的 部分定制(partial specializations) 和 定制成员(specialization members)

类模板的 部分定制(partial specializations) 和 定制成员(specialization members)

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17258777

 

类模板的部分定制, 是指使用类模板的类型(T), 但是不同种类, 如左值, 右值等;

类模板的部分定制, 和类模板定制相同, 都需要类名相同,参数相同;

定制的形参(parameter)原始模板(original template)更加匹配;

类模板有部分定制, 但函数模板没有, 函数模板只能是重载;

 

类模板的定制成员, 类模板可以单独定制成员类型, 使不同的实例化类, 使用定制的成员;

 

代码(部分定制):

 

/*
 * CppPrimer.cpp
 *
 *  Created on: 2013.12.9
 *      Author: Caroline
 */

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

template<typename T>
struct myclass{
	void print() { std::cout << "myclass!" << std::endl; }
};

//类的部分定制, 左值
template<typename T>
struct myclass<T&>{
	void print() { std::cout << "myclass! lvalue" << std::endl; }
};

//右值
template<typename T>
struct myclass<T&&>{
	void print() { std::cout << "myclass! rvalue" << std::endl; }
};

int main(void)
{
	int i(1988);
	int& ri = i;
	myclass<decltype(1988)> mc; //原始版本
	mc.print();

	myclass<decltype(ri)> mcl; //左值版本
	mcl.print();

	myclass<decltype(std::move(i))> mcr; //右值版本
	mcr.print();

	return 0;
}


输出:

 

 

myclass!
myclass! lvalue
myclass! rvalue

 

 

代码(定制成员):

 

/*
 * CppPrimer.cpp
 *
 *  Created on: 2013.12.9
 *      Author: Caroline
 */

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

template<typename T>
struct myclass{
	void print() { std::cout << "myclass!" << std::endl; }
};

//定制成员的int版本
template<>
void myclass<int>::print()
{
	std::cout << "myclass! int" << std::endl;
}

int main(void)
{
	myclass<double> mcd;
	mcd.print();

	myclass <int> mci;
	mci.print();

	return 0;
}


输出:

 

 

myclass!
myclass! int

 

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SpikeKing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值