Statically initialize anonymous union in C++

前端 未结 4 1868
有刺的猬
有刺的猬 2021-01-17 11:01

I am trying to statically initialize the following structure in Visual Studio 2010:

struct Data
{
   int x;
   union
   {
      const Data* data;
      struc         


        
4条回答
  •  花落未央
    2021-01-17 12:03

    You can make this work if all your union types are pointers, by using a void pointer as the first element of the union. All pointers can be converted to a void pointer, so your union can be initialized with an arbitrary pointer type. For the given example, you get:

    struct Data
    {
       int x;
       union
       {
          const void* unused;
          const Data* data;
          struct {int x; int y; }*; //Not sure this works written like this
          const char* asChar;
          const int*  asInt;
       };
    };
    
    static Data d1;
    static Data d2 = {2, &d1};
    static Data d3 = {1, "Hello, world!"};
    

    The other possibility is to do this in C instead. In C you can specify which part of the union is initialized. Using your original struct (and giving your structure the name asStruct):

    static Data d1;
    static Data d2 = {2, &d1};
    static Data d3 = {3, {.asStruct = {0,0}}
    

提交回复
热议问题