C++ Reflection

// class_factory.h

#include <map>
#include <string>
#include <functional>
#include <memory>

template <typename classType>
class ClassFactory
{
private:
    ClassFactory(){}
    std::map<std::string, std::function<std::shared_ptr<classType>()>> _obj_func_container;
public:

    // get class by name
    std::shared_ptr<classType>
    get_class_by_name(std::string class_name)
    {
        auto it = _obj_func_container.find(class_name);
        if (it == _obj_func_container.end())
            return nullptr;
        std::function<std::shared_ptr<classType>()> obj_func = it->second;
        return obj_func();
    }

    // regist
    void regist_class(std::string class_name, std::function<std::shared_ptr<classType>()> obj_func)
    {
        _obj_func_container[class_name] = obj_func;
    }

    // get sigleton
    static ClassFactory& get_instance()
    {
        static ClassFactory<classType> cf;
        return cf;
    }
};

// TestClass.h

#include <iostream>
#include <memory>

class TestClass
{
public:
    TestClass()
    {
        std::cout<<"TestClass()"<<std::endl;
    }
    ~TestClass()
    {
        std::cout<<"~TestClass()"<<std::endl;
    }
    void print_func()
    {
        std::cout<<"TestClass::print_func"<<std::endl;
    }
};


std::shared_ptr<TestClass> creat_testclass()
{
    return std::make_shared<TestClass>();
}

// main.cpp
#include <iostream>

#include "class_factory.h"
#include "TestClass.h"

using namespace std;

int main()
{
    ClassFactory<TestClass>& cf = ClassFactory<TestClass>::get_instance();
    cf.regist_class("TestClass", creat_testclass);

    std::shared_ptr<TestClass> t =  cf.get_class_by_name("TestClass");
    t->print_func();

    return 0;
}
 

运行截图



  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++ 本身没有内置的反射机制,但可以通过一些技术手段实现类似的功能,称为 C++ 反射。 C++ 反射是指在运行时获取和操作类型信息的能力。通过反射,可以在运行时查询类的成员、调用方法、访问属性等。 下面介绍几种常见的实现 C++ 反射的方法: 1. 使用宏(macros):通过宏定义来生成代码,使得类的信息在编译时就可以得到。该方法通常需要手动编写宏,并且在每个需要反射的类中添加相应的宏定义。 2. 使用模板元编程(template metaprogramming):利用 C++ 的模板特性和编译期计算能力,通过模板实现类的信息提取和操作。这种方法通常需要编写复杂的模板代码,并且对于复杂的类型和操作可能不够灵活。 3. 使用第三方库:有一些第三方库提供了完善的反射机制,例如 Boost.Reflection、Qt 的元对象系统(Meta-Object System)等。这些库提供了更高级的功能和更方便的接口,可以简化反射的实现和使用过程。 无论使用哪种方法,实现 C++ 反射都需要对类的结构和成员进行解析和存储,以便在运行时进行查询和操作。这通常需要额外的代码和数据结构,因此在选择使用反射时需要权衡代码复杂性和功能需求。 需要注意的是,C++ 反射可能会引入一定的性能开销和代码复杂性。在设计和使用反射时,需要考虑其对性能和代码可维护性的影响,并确保反射的使用是必要且合适的。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值