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

前端 未结 28 1627
感动是毒
感动是毒 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:50

    You need to look at what you are trying to do, and if RTTI will satisfy your requirements. I've implemented my own pseudo-reflection for some very specific purposes. For example, I once wanted to be able to flexibly configure what a simulation would output. It required adding some boilerplate code to the classes that would be output:

    namespace {
      static bool b2 = Filter::Filterable::Register("MyObject");
    } 
    
    bool MyObj::BuildMap()
    {
      Filterable::AddAccess("time", &MyObj::time);
      Filterable::AddAccess("person", &MyObj::id);
      return true;
    }
    

    The first call adds this object to the filtering system, which calls the BuildMap() method to figure out what methods are available.

    Then, in the config file, you can do something like this:

    FILTER-OUTPUT-OBJECT   MyObject
    FILTER-OUTPUT-FILENAME file.txt
    FILTER-CLAUSE-1        person == 1773
    FILTER-CLAUSE-2        time > 2000
    

    Through some template magic involving boost, this gets translated into a series of method calls at run-time (when the config file is read), so it's fairly efficient. I wouldn't recommend doing this unless you really need to, but, when you do, you can do some really cool stuff.

提交回复
热议问题