我将我的疑问提炼为以下代码
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
可以简单地替换为boost
: boost::is_base_of http://www.boost.org/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)