通过基类专门化类模板

时间:2012-11-27 08:28:16

标签: c++ templates

我已将我的疑问提炼到以下这段代码

struct base {};
struct derived : public base {};

template <class T>
struct Type { };

template <> struct Type<base> {
  typedef float mytype;
};

typename Type<base>::mytype a=4.2;    // this works
typename Type<derived>::mytype a=4.2; // this doesnt

有人可以解释为什么我不能用derived来实例化类模板对象,并建议一个简单的方法来实现它。对于我感兴趣的实际问题,有许多派生类,我想使用它来实例化模板类对象和/或使用typedef。它们太多了,而不是我想要单独专业化的东西。

编辑:忘记提及,我的不好,这需要是C ++ 03

2 个答案:

答案 0 :(得分:4)

#include <iostream>
#include <type_traits>

struct base { };
struct derived : base { };

template<typename T, bool = std::is_base_of<base, T>::value>
struct Type { };

template<typename T>
struct Type<T, true>
{
   typedef float mytype;
};

int main()
{
   Type<base>::mytype a1 = 4.2f;
   Type<derived>::mytype a2 = 8.4f;
   std::cout << a1 << '\n' << a2 << '\n';
}

在C ++ 03中,std可以简单地替换为boostboost::is_base_of

答案 1 :(得分:2)

具有不同模板参数的模板类的两个实例是完全不相关的类类型。 Type<derived>Type<base>没有任何关系,这当然意味着它不使用专门化并且从主模板中实例化。主模板没有嵌套类型mytype