4

Is there a way to get the number of members of a union in C++? For example:

union U
{
    int a;
    double b;
    char c;
};

int main()
{
    std::cout << std::union_members_count<U>::value << std::endl;  // prints 3
}

Of course, std::union_members_count<> is fictional.

If there is a way, how do I implement/use it?

hermit.crab
  • 852
  • 1
  • 8
  • 20
  • 6
    There is no such functionality in C++. You will have to wait and hope for reflection proposals to go through. Alternatively use external tools such as clang-query and some preprocessing script. – nwp Mar 13 '18 at 12:35
  • i'm working with protocol where each message has fields that are identifiable from a union unique for each message. so the maximum number of fields for a message is dependent on the number of members for the union associated with that message. Unfortunately, the encoder for the message is based on a fixed array whose size is a template parameter. so i have to manually supply the number of members of the union as a template argument for the encoder for each message. If the number of members in the union changes, then i have to change the value for the template argument of the encoder. – hermit.crab Mar 13 '18 at 13:07
  • It would be convenient if the size of the encoder array can be automatically deduced based on the number of members of the union, since the protocol has a lot of message types. the encoder, unfortunately, has been in existence for about 10+ years already, and it has no unit tests. so, changing the encoder to use a dynamic array is dangerous. – hermit.crab Mar 13 '18 at 13:08

1 Answers1

7

No, this is not possible in C++.

C++ does not have reflection, a feature for code that describes itself.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055