C++反射机制实现

直接上代码

#include <iostream>
#include <map>

class Base
{
public:
    virtual void hello() const = 0;
};

class A : public Base
{
public:
    A()
    {
        std::cout << "A construct" << std::endl;
    }

    void hello() const override
    {
        std::cout << "A hello" << std::endl;
    }
};

class B : public Base
{
public:
    B()
    {
        std::cout << "B construct" << std::endl;
    }

    void hello() const override
    {
        std::cout << "B hello" << std::endl;
    }
};

class BaseFactory
{
public:
    virtual Base *create() const = 0;
};

template <typename T>
class Factory : public BaseFactory
{
public:
    Base *create() const override
    {
        return new T;
    }
};

int main(int argc, char const *argv[])
{
    std::cout << "----- test basic class -----" << std::endl;
    Base *a = new A();
    a->hello();
    Base *b = new B();
    b->hello();

    std::cout << "----- test Factory class -----" << std::endl;
    BaseFactory *f = new Factory<A>;
    Base *a1 = f->create();
    a1->hello();

    std::cout << "----- test Reflection -----" << std::endl;
    std::map<std::string, BaseFactory *> factoryMap;
    factoryMap["A"] = new Factory<A>;
    factoryMap["B"] = new Factory<B>;
    factoryMap["A"]->create()->hello();
    factoryMap["B"]->create()->hello();

    return 0;
}

运行结果

posted @ 2023-02-22 10:54  爱弹钢琴的卡农  阅读(42)  评论(0)    收藏  举报