简体   繁体   English

通过基类专门化类模板

[英]Specializing a class template by a base class

I have distilled my doubt to this following piece of code我已经对以下这段代码产生了怀疑

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

Could anyone explain why I cannot intantiate the class template object with derived and suggest a simple way to do it.谁能解释为什么我不能用derived的类模板对象并提出一种简单的方法来做到这一点。 For the actual problem that I am interested in there are many derived classes using which I want to intantiate template class objects and/or use typedefs.对于我感兴趣的实际问题,我想使用许多派生类来实例化模板类对象和/或使用 typedef。 There are too many of them than what I would want to specialize individually.它们太多了,我想单独专攻。

EDIT: Forgot to mention, my bad, this needs to be C++03编辑:忘了提,我的错,这需要是 C++03

#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';
}

In C++03, std can be trivially replaced with boost : boost::is_base_of在 C++03 中, std可以简单地替换为boostboost::is_base_of

Two instantiations of a template class with different template arguments are totally unrelated class types.具有不同模板参数的模板类的两个实例是完全不相关的类类型。 Type<derived> has no relation whatsoever to Type<base> , which of course means it doesn't use the specialisation and is instantiated from the primary template. Type<derived>Type<base>没有任何关系,这当然意味着它不使用特化并从主模板实例化。 The primary template has no nested type mytype .主模板没有嵌套类型mytype

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM