Iterating over a struct in C++

前端 未结 8 755
说谎
说谎 2020-11-28 07:08

I have a structure

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;

I want to iterate over each an every member of the structure

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 07:29

    As suggested by @Paul I use BOOST_FUSION_ADAPT_STRUCT with a self written for_each_member function :

    /**
     * \brief Allows iteration on member name and values of a Fusion adapted struct.
     * 
     *  
     * BOOST_FUSION_ADAPT_STRUCT(ns::point,
     *      (int, x)
     *      (int, y)
     *      (int, z));
     *
     * template
     * print_name_and_value(const char* name, T& value) const {
     *    std::cout << name << "=" << value << std::endl;
     * } 
     *
     * 
     * int main(void) {
     *  
     *  ns::point mypoint;
     *
     *  
     *      boost::fusion::for_each_member(mypoint, &print_name_and_value);
     *
     *
     * }
     *
     */
    #ifndef BOOST_FUSION_FOR_EACH_MEMBER_HPP
    #define BOOST_FUSION_FOR_EACH_MEMBER_HPP
    
    #include 
    
    #include 
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    namespace boost { namespace fusion {
    
    namespace detail {
    
      template 
      inline void
      for_each_member_linear(First const& first,
          Last const& last,
          F const& f,
          boost::mpl::true_) {}
    
      template 
      inline void
      for_each_member_linear(First const& first,
          Last const& last,
          F const& f,
          boost::mpl::false_) {
    
          f(
                    extension::struct_member_name<
                        typename First::seq_type, First::index::value
                    >::call(),
                    *first
                );
    
          for_each_member_linear(
              next(first),
              last,
              f,
              result_of::equal_to< typename result_of::next::type, Last>()
          );
      }
    
      template 
      inline void
      for_each_member(Sequence& seq, F const& f) {
    
        detail::for_each_member_linear(
          fusion::begin(seq),
          fusion::end(seq),
          f,
          result_of::equal_to<
            typename result_of::begin::type,
            typename result_of::end::type>()
        );
      }
    
    }
    
      template 
      inline void
      for_each_member(Sequence& seq, F f) {
        detail::for_each_member(seq, f);
      }
    
    }}
    
    #endif 
    

提交回复
热议问题