想知道是否有可能有一个模板函数可以根据类型是否派生自特定类进行分支。以下是我的大致想法:
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
}
}
关于C++ 编译时类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14094214/