Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

class message_a
{
  long long identifier;
  double some_value;
  class something_else;
  ...//many more data members
}

Is it possible to write a macro/meta-program that would allow calculating the number of data members within the class at compile time?

//eg:

class message_b
{
  long long identifier;
  char foobar;
}


bitset<message_b::count_members> thebits;

I am not familiar with C++ meta programming, but could boost::mpl::vector allow me to accomplish this type of calculation?

like image 375
MW_dev Avatar asked Jul 27 '11 12:07

MW_dev


1 Answers

as others already suggested, you need Boost.Fusion and its BOOST_FUSION_DEFINE_STRUCT. You'll need to define your struct once using unused but simple syntax. As result you receive required count_members (usually named as size) and much more flexibility than just that.

Your examples:

Definition:

BOOST_FUSION_DEFINE_STRUCT(
    (), message_a,
    (long long, identifier),
    (double, some_value)
)

usage:

message_a a;
size_t count_members = message_a::size;
like image 105
Andriy Tylychko Avatar answered Sep 28 '22 03:09

Andriy Tylychko