如何强制模板参数T
成为特定类的子类Baseclass
?
像这样的东西:
template <class T : Baseclass> void function(){
T *object = new T();
}
使用 C++11 兼容的编译器,您可以执行以下操作:
template<class Derived> class MyClass {
MyClass() {
// Compile-time sanity check
static_assert(std::is_base_of<BaseClass, Derived>::value, "Derived not derived from BaseClass");
// Do other construction related stuff...
...
}
}
我已经在 CYGWIN 环境中使用 gcc 4.8.1 编译器对此进行了测试 - 所以它也应该在 *nix 环境中工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)