类模板的完全特例化和非完全特例化

有关类模板和函数模板的一些概念:

1、函数模板不支持模板参数给默认值(C99标准),类模板支持参数给默认值。

2、类模板有选择性实例化。

3、类中部分函数特例化时,一定要提供成员方法的模板。

4、成员方法的特例化不能在类外定义(语法不支持)。

5、类模板不能进行模板的实参推演,实参推演只针对函数模板。

6、出了编译器自动生成的成员函数之外,其他成员方法的模板完全可以代替普通的成员方法。


代码示例:

#include <iostream>
using namespace std;

//类模板
template<typename T>
class Test
{
public:
	void test()
	{
		cout << "Test::test" << endl;
	}
};

//完全特例化
template<>
class Test<char *>
{
public:
	void test()
	{
		cout << "Test<char *>::test" << endl;
	}
};

//提供针对指针的非完全特例化版本
template<typename T>
class Test<T*>
{
public:
	void test()
	{
		cout << "Test<T*>::test" << endl;
	}
};

//返回值void 带有一个类型为T类型的参数的函数指针 提供非完全特例化
template<typename E>
class Test<void(*)(E)>
{
public:
	void test()
	{
		cout << "Test<void(*)(E)::test" << endl;
	}
};

template<typename E>
class Test<void(E)>
{
public:
	void test()
	{
		cout << "Test<void(E)::test" << endl;
	}
};

void func1(int data)
{
	cout << "call func1" << endl;
}

void func2(double data)
{
	cout << "call func2" << endl;
}

void _cdecl pfunc3(int)
{
	cout << "call pfunc3" << endl;
}

int main()
{
	Test<int> t1;
	t1.test();

	Test<char *> t2;
	t2.test();

	Test<float *> t3;
	t3.test();

	Test<void(*)(int)> t4;
	t4.test();

	Test<void (int)> t5;
	t5.test();

	typedef void (*PFUNC)(int);//函数指针类型
	PFUNC pfunc = &func1;
	(*pfunc)(10);

	typedef void (PFUNC2)(int);//函数类型
	PFUNC2 *pfunc2 = &func1;
	(*pfunc2)(20);

	PFUNC2 pfunc3;
	pfunc3(10);

	return 0;
}

运行结果:




猜你喜欢

转载自blog.csdn.net/moon5555/article/details/79386624
今日推荐