[英]C++ compile-time type checking
想知道是否有可能根据类型是否派生自特定类而分支的模板函数。 这大致就是我的想法:
class IEditable {};
class EditableThing : public IEditable {};
class NonEditableThing {};
template<typename T>
RegisterEditable( string name ) {
// If T derives from IEditable, add to a list; otherwise do nothing - possible?
}
int main() {
RegisterEditable<EditableThing>( "EditableThing" ); // should add to a list
RegisterEditable<NonEditableThing>( "NonEditableThing" ); // should do nothing
}
如果有人有任何想法让我知道! :)
编辑:我应该添加,我不想实例化/构造给定的对象只是为了检查其类型。
这是std::is_base_of
的实现:
#include <type_traits>
template <typename T>
void RegisterEditable( string name ) {
if ( std::is_base_of<IEditable, T>::value ) {
// add to the list
}
}
正如@Lightness所指出的,type_traits是答案。
C ++ 11包含了boost
type_trait的功能: http : //en.cppreference.com/w/cpp/types/is_base_of
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.