类定义之外的部分模板特化

Jof*_*sey 5 c++ templates

我可以在类声明中使用部分模板特化

template<class T1, class T2>
struct A
{
    void foo() { cout << "general"; }
};

template<class T1>
struct A<T1, int>
{
    void foo() { cout << "partial specialization"; }
};
Run Code Online (Sandbox Code Playgroud)

但是当我试图在类声明之外做这件事时

template<class T1, class T2>
struct A
{
    void foo();
};


template<class T1, class T2>
void A<T1, T2>::foo() { cout << "general"; }

template<class T1>
void A<T1, int>::foo() { cout << "partial specialization"; }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

不完整类型 «struct A < T1, int >» 的无效使用

当您想重新定义所有成员时,使用第一种方法不是问题,但是如果您只想重新定义一个方法而不为所有其他方法重复代码怎么办?

那么,是否可以在类定义之外使用部分模板特化?

Pio*_*ycz 3

当您想要重新定义所有成员时,使用第一种方法不是问题,但是如果您只想重新定义一个方法而不为所有其他方法重复代码怎么办?

这就是可以使用特征技术的地方。请参阅http://www.boost.org/community/generic_programming.html#traits

一些用法:

template <class T1, class T2>
struct ATraits {
   static void foo() {}
};

template <class T1>
struct ATraits<T1,int> {
   static void foo() {}
};

template <class T1, class T2>
struct A {
   void foo() { ATraits<T1,T2>::foo(); }
};
Run Code Online (Sandbox Code Playgroud)