繁体   English   中英

通过基类专门化类模板

[英]Specializing a class template by a base class

我已经对以下这段代码产生了怀疑

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

#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

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

暂无
暂无

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

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