基于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

使用:

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

场景是什么?

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

问题:

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

相关推荐
成为大佬先秃头1 分钟前
前后分离项目:整合JWT+Shiro
java·springboot·shiro·jwt
y = xⁿ5 分钟前
【Leet Code 】滑动窗口
java·算法·leetcode
WBluuue7 分钟前
数据结构与算法:二项式定理和二项式反演
c++·算法
day day day ...17 分钟前
MyBatis条件误写引发的查询条件污染分析与防范
java·服务器·tomcat
dr_yingli22 分钟前
fMRI(3-1)报告(个体化报告)生成器说明
开发语言·matlab
hrhcode22 分钟前
【java工程师快速上手go】一.Go语言基础
java·开发语言·golang
yashuk24 分钟前
C语言 vs. C++ ,哪个更适合初学者?
c语言·c++·面向对象编程·初学者·学习路径
-许平安-30 分钟前
MCP项目笔记十(客户端 MCPClient)
c++·笔记·ai·raii·mcp·pluginapi·plugin system
一只旭宝33 分钟前
【C++ 入门精讲2】函数重载、默认参数、函数指针、volatile | 手写笔记(附完整代码)
c++·笔记
2601_9507039436 分钟前
Spring IoC入门实战:XML与注解双解
java