C ++编译时类型检查 [英] C++ compile-time type checking

查看:94
本文介绍了C ++编译时类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否可以有一个模板函数,可以根据类型是否派生自一个特定的类分支。这大概是我在想什么:

Was wondering if it's possible to have a template function that can branch depending on whether the type is derived from a particular class. Here's roughly what I'm thinking:

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
}

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

If anyone has any ideas let me know! :)

编辑:我应该添加,我不想实例化/构造给定的对象只是检查它的类型。

I should add, I don't want to instantiate / construct the given object just to check its type.

推荐答案

这是一个实现 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 ++编译时类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆