通过基类专门化类模板 [英] 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
有人可以解释为什么我不能用 derived
并建议一个简单的方法来做。对于我感兴趣的实际问题有许多派生类使用它我想要模板类对象和/或使用typedefs。
Could anyone explain why I cannot intantiate the class template object with derived
and suggest a simple way to do it. 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. There are too many of them than what I would want to specialize individually.
编辑:忘记了,我的坏,这需要是C ++ 03
Forgot to mention, my bad, this needs to be 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
可以简单地替换为 boost
: boost :: is_base_of
In C++03, std
can be trivially replaced with boost
: boost::is_base_of
这篇关于通过基类专门化类模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!