C++ macro/metaprogram to determine number of members at compile time

后端 未结 5 1559
鱼传尺愫
鱼传尺愫 2020-12-18 07:15

I am working on an application with a message based / asynchronous agent-like architecture. There will be a few dozen distinct message types, each represented by C++ types.<

5条回答
  •  清歌不尽
    2020-12-18 07:43

    No, there is no way in C++ to know the names of all members or how many members are actually there.

    You could store all types in a mpl::vector along in your classes but then you face the problem of how to turn them into members with appropriate names (which you cannot achieve without some macro hackery).

    Using std::tuple instead of PODs is a solution that generally works but makes for incredible messy code when you actually work with the tuple (no named variables) unless you convert it at some point or have a wrapper that forwards accessors onto the tuple member.

    class message {
    public:
      // ctors
      const int& foo() const { return std::get<0>(data); }
      // continue boiler plate with const overloads etc
    
      static std::size_t nun_members() { return std::tuple_size::value; }
    private:
      std::tuple data;
    };
    

    A solution with Boost.PP and MPL:

    #include 
    #include 
    #include 
    #include 
    
    struct Foo {
      typedef boost::mpl::vector types;
    
    // corresponding type names here
    #define SEQ (foo)(bar)(baz)
    #define MACRO(r, data, i, elem) boost::mpl::at< types, boost::mpl::int_ >::type elem;
    BOOST_PP_SEQ_FOR_EACH_I(MACRO, 0, SEQ)
    
    };
    
    int main() {
      Foo a;
      a.foo;
    }
    

    I didn't test it so there could be bugs.

提交回复
热议问题