How can I add reflection to a C++ application?

前端 未结 28 1657
感动是毒
感动是毒 2020-11-21 11:25

I\'d like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I\'m talking native C++ here, not managed C++, which has reflection

28条回答
  •  别跟我提以往
    2020-11-21 11:55

    There are two kinds of reflection swimming around.

    1. Inspection by iterating over members of a type, enumerating its methods and so on.

      This is not possible with C++.
    2. Inspection by checking whether a class-type (class, struct, union) has a method or nested type, is derived from another particular type.

      This kind of thing is possible with C++ using template-tricks. Use boost::type_traits for many things (like checking whether a type is integral). For checking for the existance of a member function, use Is it possible to write a template to check for a function's existence? . For checking whether a certain nested type exists, use plain SFINAE .

    If you are rather looking for ways to accomplish 1), like looking how many methods a class has, or like getting the string representation of a class id, then i'm afraid there is no Standard C++ way of doing this. You have to use either

    • A Meta Compiler like the Qt Meta Object Compiler which translates your code adding additional meta informations.
    • A Framework constisting of macros that allow you to add the required meta-informations. You would need to tell the framework all methods, the class-names, base-classes and everything it needs.

    C++ is made with speed in mind. If you want high-level inspection, like C# or Java has, then I'm afraid i have to tell you there is no way without some effort.

提交回复
热议问题