C++ 编译时类型检查

标签 c++ templates

想知道是否有可能有一个模板函数可以根据类型是否派生自特定类进行分支。以下是我的大致想法:

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/

相关文章:

c++ - 在命名空间内声明和定义 - 不确定它是否有效,因为它是正确的还是偶然的

c++ - Swift 中的类

c++ - 在Nuke中翻转OpenEXR RgbaOutputFile

c++ - 依靠枚举 C++ 自动

c++ - 将参数转发给模板成员函数

c++ - 当堆栈为空时,在(模板化的)堆栈弹出方法中做什么?

c++ - 尝试使用未知类型的模板非类型参数

c++ - NURBS 和 opengl 4.2 内核怎么样?

C#模板参数作为模板接口(interface)

c++ - 如何使用 std::array 模拟 C 数组初始化 "int arr[] = { e1, e2, e3, ... }"行为?