代码改变世界

类模板和函数模板

2014-07-18 22:07  钱吉  阅读(155)  评论(0编辑  收藏  举报

类的成员函数是模板函数时的特例化:

class Test
{
public:
	Test() {};
	~Test() {};

	template<typename T> void calc(T val);
	/*{
		cout<<val*2<<endl;
	}*/
};
template<typename T>
void Test::calc(T val)
{
	cout<<val*2<<endl;
}
template<>
void Test::calc(int val)
{
	cout<<val*4<<endl;
}

int v1 = 2;
double v2 = 2.5;
Test t;
t.calc(v1);
t.calc(v2);

参考:http://www.cnblogs.com/hailong/articles/1977370.html