类定义之外的部分模板专门化 [英] Partial template specialization outside class definition

查看:145
本文介绍了类定义之外的部分模板专门化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can use partial template specialization inside class declaration

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

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

但是当我试图在类声明之外执行它

But when I'm trying to do it outside class declaration

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"; }

我收到以下错误:

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

invalid use of incomplete type «struct A < T1, int >»

当你想重新定义所有成员时,使用第一种方法不是一个问题,

It's not a problem to use the first approach when you want to redefine all members, but what if you want redefine only one method without code duplication for all others?

所以,是否可以在类定义之外使用部分模板专门化?

推荐答案


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

It's not a problem to use the first approach when you want to redefine all members, but what if you want redefine only one method without code duplication for all others?

这里可以使用traits技术。请参见 http://www.boost.org/community/generic_programming.html#traits

This is where traits technique can be used. See 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(); }
};

这篇关于类定义之外的部分模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆