“Poor Man's Reflection” (AKA bottom-up reflection) in C++

后端 未结 3 1721
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 15:01

I am implementing some rudimentary reflection in C++ for an ultra modular architecture where virtually all features are loaded as plugins and interpreted dynamically at run-

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 15:25

    You can try this.. Also look through: http://en.cppreference.com/w/cpp/header/type_traits

    #include 
    #include 
    
    #ifdef _MSC_VER
    #define __FUNC_NAME__ __FUNCTION__
    #else
    #define __FUNC_NAME__ __PRETTY_FUNCTION__
    #endif // _MS_VER
    
    #ifdef _MSC_VER
    #define RF_DETAIL  std::string GetDetail() {return __FUNCSIG__;}
    #else
    #define RF_DETAIL  std::string GetDetail() {return __FUNC_NAME__;}
    #endif
    
    
    #define RF_CLASS   std::string GetClass() {\
                             const std::string name = __FUNC_NAME__;\
                             std::string::size_type beg = name.find_first_of(" "), end = name.find_first_of("<");\
                             if (!end) end = name.find_first_of("::");\
                             return name.substr(beg + 1, end - beg - 1); }
    
    #define RF_TYPE    auto GetType() -> std::remove_reference::type {return std::move(std::remove_reference::type()); }
    
    #define RF_TYPE_PTR    auto GetTypePtr() -> decltype(this) {return this;}
    
    template
    class Foo
    {
        public:
            RF_DETAIL;
            RF_CLASS;
            RF_TYPE;
            virtual ~Foo(){}
    };
    
    template
    class Meh : public Foo
    {
        public:
            RF_DETAIL;
            RF_CLASS;
            RF_TYPE;
            virtual ~Meh(){}
    };
    
    class Go
    {
        public:
            RF_DETAIL;
            RF_CLASS;
            RF_TYPE;
            RF_TYPE_PTR;
    };
    
    int main()
    {
        Foo f;
        std::cout< g;
        std::cout<

    Prints:

    std::string Foo::GetDetail() [with T = int; std::string = std::basic_string]
    
    Foo
    
    
    std::string Meh::GetDetail() [with T = int; std::string = std::basic_string]
    
    Meh
    
    
    Foo::GetClass()
    

提交回复
热议问题