c++模板类如何定义模板成员函数

2 篇文章 0 订阅
1 篇文章 0 订阅

最近跟网上一个解决一个模板问题

其实他在用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

    • 0
      点赞
    • 1
      收藏
      觉得还不错? 一键收藏
    • 0
      评论
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值