有關(guān)模板的語法很多很雜,無法一一列舉,在此僅測試幾個簡單常用的語法。
以下有關(guān)模板的語法分別使用 Dev-CPP4991、VC++6.0 和 Intel C++8.0 進(jìn)行測試,DEVCPP和ICC都能完全通過測試,VC++6有部分通不過測試。
1. 模板類靜態(tài)成員
template <typename T> struct testClass {
static int _data;
};
template<> int testClass<char>::_data = 1;
template<> int testClass<long>::_data = 2;
int main( void ) {
cout << boolalpha << (1==testClass<char>::_data) << endl;
cout << boolalpha << (2==testClass<long>::_data) << endl;
}
2. 模板類偏特化
template <class I, class O> struct testClass {
testClass() { cout << "I, O" << endl; }
};
template <class T> struct testClass<T*, T*> {
testClass() { cout << "T*, T*" << endl; }
};
template <class T> struct testClass<const T*, T*> {
testClass() { cout << "const T*, T*" << endl; }
};
int main( void ) {
testClass<int, char> obj1;
testClass<int*, int*> obj2;
testClass<const int*, int*> obj3;
}
[注]: VC++6 編譯不通過
3. function template partial order
template <class T> struct testClass {
void swap( testClass<T>& ) { cout << "swap()" << endl; }
};
template <class T> inline void swap( testClass<T>& x, testClass<T>& y ) {
x.swap( y );
}
int main( void ) {
testClass<int> obj1;
testClass<int> obj2;
swap( obj1, obj2 );
}
[注]: VC++6 編譯不通過
4. 類成員函數(shù)模板
struct testClass {
template <class T> void mfun( const T& t ) {
cout << t << endl;
}
template <class T> operator T() {
return T();
}
};
int main( void ) {
testClass obj;
obj.mfun( 1 );
int i = obj;
cout << i << endl;
}
[注]: 對于第二個成員函數(shù)模板,VC++6 運(yùn)行異常
5. 缺省模板參數(shù)推導(dǎo)
template <class T> struct test {
T a;
};
template <class I, class O=test<I> > struct testClass {
I b;
O c;
};
6. 非類型模板參數(shù)
template <class T, int n> struct testClass {
T _t;
testClass() : _t(n) {
}
};
int main( void ) {
testClass<int,1> obj1;
testClass<int,2> obj2;
}
7. 空模板參數(shù)
template <class T> struct testClass;
template <class T> bool operator==( const testClass<T>&, const testClass<T>& ) {
return false;
};
template <class T> struct testClass {
friend bool operator== <>( const testClass&, const testClass& );
};
[注]: VC++6 編譯不通過
8. 模板特化
template <class T> struct testClass {
};
template <> struct testClass<int> {
};
9.
template <template <class T> class X>
struct Widget{
};
[注]: VC++6 編譯不通過
10. [hpho]提供的一個事例
struct Widget1 {
template<typename T>
T foo(){}
};
template<template<class T>class X>
struct Widget2{
};
[注]: VC++6 編譯不通過