Search code examples
c++macrosmetaprogramming

Is there a way to count member variable of a class in compile time?


What I want to do is to check member variable count of a class, as some newbie might write too much member variable to read. Is there some way to get it?

We did do code reviews, but a static_assert(GET_MEM_VAR_COUNT(ClassA) < 10) might be more straight and clear.


Solution

  • Until we get reflection, you are stuck using another tool to check the number of members in a class.

    We have a few crude ways to get reflection now, with many limitations. If you only have a data struct, then you can use Boost Fusion to define your class such that you can assert on its size, for example:

    #include <string>
    
    #include <boost/fusion/include/define_struct.hpp>
    #include "boost/mpl/size.hpp"
    
    BOOST_FUSION_DEFINE_STRUCT(
        (my_namespace), my_class,
        (std::string, member1)
        (int, member2)
        (int, member3)
        (double, member4)
    //Uncomment me to trigger assert  (double, member5)
    )
    
    static_assert(boost::mpl::size<my_namespace::my_class>::type::value < 5, "Classes must have fewer than 5 members");
    

    Demo