基于C++的反射功能

需求:

利用C++的发射机制,实现根据字符串创建实例对象。

代码:

复制代码
#ifndef OBJECT_H
#define OBJECT_H

#include <string>
#include <map>

typedef void* (*Constructor)();

class CObjectFactory
{
public:
    static void registerClass(std::string className, Constructor constructor)
    {
        constructors()[className] = constructor;
    }

    static void* createObject(const std::string& className)
    {
        Constructor constructor = NULL;

        if(constructors().find(className) != constructors().end())
            constructor = constructors().find(className)->second;

        if ( constructor == NULL )
            return NULL;

        return (*constructor)();
    }

private:
    inline static std::map<std::string, Constructor>& constructors()
    {
        static std::map<std::string, Constructor> instance;
        return instance;
    }
};


#define REGISTER_CLASS(class_name) \
class class_name##Helper { \
public: \
    class_name##Helper() \
    { \
        CObjectFactory::registerClass(#class_name, class_name##Helper::creatObjFunc); \
    } \
    static void* creatObjFunc() \
    { \
        return new class_name; \
    } \
}; \
class_name##Helper class_name##helper;


#endif

使用:

类实现的时候,进行注册。

场景是什么?

类似与这种流程图,有很多算子,我在注册的时候,将算子的类名作为参数,拖拽结束后,获取类名字符串,自动创建对象。

问题:

构造的时候,没办法传参。

相关推荐
文丑颜不良啊6 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI7 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
wuyk5557 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel
文丑颜不良啊7 小时前
LeetCode3421~3440题目解析
java·leetcode
code2cat8 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
whitelbwwww9 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
码云社区9 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区10 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件10 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水10 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring