プログラミング > C++ > テンプレート部分特殊化

テンプレート部分特殊化に関するメモ



部分特殊化とは

通常なんでもござれなテンプレートクラス(class,struct,enum,union)に
特定の型にだけ別対応させたいときに使う
(ちなみにクラスでなくテンプレート関数にはオーバーロードで対応する)
#include <iostream>
 
using namespace std;
 
template<class T, class C>
struct Foo
{ Foo(T,C) { cout << "template" << endl;} };
 
template<class T>
struct Foo<T, int>
{ Foo(T,int) { cout << "special int" << endl; } };
 
template<>
struct Foo<char, char>
{ Foo(char,char) { cout << "special char" << endl; } };
 
 
int main() {
	char ca = 'a', cb = 'b';
	int ia = 10, ib = 20;
	double da = 1.0, db = -2.0;
 
	Foo<char,char>     f1(ca, cb); // special char
	Foo<int,int>       f2(ia, ib); // special int
	Foo<double,double> f3(da, db); // template
	Foo<int,double>    f4(ia, db); // template
 
	return 0;
}
 

ポインタ型・参照型・配列型の部分特殊化

#include <iostream>
 
using namespace std;
 
template<class T>
struct Foo
{ Foo(T) { cout << "template" << endl;} };
 
template<class T>
struct Foo<T*>
{ Foo(T*) { cout << "special T*" << endl; } };
 
template<class T>
struct Foo<T&>
{ Foo(T&) { cout << "special T&" << endl; } };
 
template<class T>
struct Foo<T[]>
{ Foo(T[]) { cout << "special T[]" << endl; } };
 
int main() {
 
	int n = 10;
	int m[5];
 
	Foo<int>        f1(n);
	Foo<int*>       f2(&n);
	Foo<int&>       f3(n);
	Foo<int[]>      f4(m);
 
	return 0;
}
 
最終更新:2014年10月10日 16:55