最近跟网上一个解决一个模板问题
其实他在用g++编译器写模板定义成员函数,我在vs 05的c++编译器上写,然后我测试模板的结果是:
特例模板不可以在类外定义,不管是在头文件还是cpp文件都要报错,然后跟他说让他写在类中(当时不知道他在用g++编译器),
于是悲剧的问题出来了……他那个老是报没在未命名空间类域中这样的错误。
后来,还是他去问了同学…………其实只要在类中申明模板函数特例,在.tem文件中实现,而且不用在函数后加特例类型,
void testclass<type > func()
{
}
哎,最后我试了一下用这样的方式在vs05下是不能编译通过的。所以在vs05编译器不能使用那样的方法,其实一般写模板类直接都整在一个模板类中实现就行了……虽然臃肿,但是不会出错,还是挺好的…………
最后再放上一段IBM那边的示例代码…………话说看了之后也没什么感觉…………
#include <iostream> using namespace std; template<class T> class X { public: template<class U> class Y { public: template<class V> void f(U,V); void g(U); }; }; template<class T> template<class U> template<class V> void X<T>::Y<U>::f(U, V) { cout << "Template 1" << endl; } template<class T> template<class U> void X<T>::Y<U>::g(U) { cout << "Template 2" << endl; } template<> template<> void X<int>::Y<int>::g(int) { cout << "Template 3" << endl; } template<> template<> template<class V> void X<int>::Y<int>::f(int, V) { cout << "Template 4" << endl; } template<> template<> template<> void X<int>::Y<int>::f<int>(int, int) { cout << "Template 5" << endl; } // template<> template<class U> template<class V> // void X<char>::Y<U>::f(U, V) { cout << "Template 6" << endl; } // template<class T> template<> // void X<T>::Y<float>::g(float) { cout << "Template 7" << endl; } int main() { X<int>::Y<int> a; X<char>::Y<char> b; a.f(1, 2); a.f(3, 'x'); a.g(3); b.f('x', 'y'); b.g('z'); }
- The compiler would not allow the template specialization definition that would output"Template 6" because it is attempting to specialize a member (functionf()) without specialization its containing class (Y).
- The compiler would not allow the template specialization definition that would output"Template 7" because the enclosing class of classY (which is classX) is not explicitly specialized.
结果是:
Template 5Template 4Template 3Template 1Template 2