2012-12-30 86 views
4

想知道是否有可以分支的模板函数,具体取决于类型是否从特定类派生。这大致是我在想什么:C++编译时类型检查

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 
} 

如果有人有任何想法,让我知道! :)

编辑:我要补充,我不想实例/构造给定的对象只是为了检查其类型。

+1

http://www.boost.org/doc/libs/1_52_0/libs/ type_traits/doc/html/boost_typetraits/reference/is_base_of.html –

+0

有趣 - 将检查出来,听起来很有希望。 – QuadrupleA

回答

4

下面是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 
    } 
} 
+0

谢谢 - 刚刚把我的头缠在了type_traits周围,那正是我想要的。不幸的是,它引发了我想到的设计中的另一个问题,但我会看看是否可以单独分类。 – QuadrupleA