How to initialize a member of a union structure inside a structure in C ++?

I want to migrate a parameter lookup table, which is an array of structures in C to C ++. I read a few questions and realized that a C structure initializer is not allowed in C ++. How can this be ported to C ++?

typedef struct {
  char const *property;
  int count;
} TYPE2;

typedef struct {
  int Address;             
  char const *Name;         
  union
  {
    TYPE1 foo;
    TYPE2 bar;
  }u;
} PARAMS;

//Initialize table:
const PARAMS paramTbl[] =
{
  {0x1000, "Param 1", {.bar = {"abc",0}}}, //So on ..
  .
  . 
}

Any help appreciated.

+4
source share
1 answer

You may have a struct / union constructor to initialize with a given value.

struct PARAMS {
  PARAMS(int address, const char *name, const TYPE1 &f) :
                    Address(address), Name(name), u(f)
  {
  }
  PARAMS(int address, const char *name, const TYPE2 &b) :
                    Address(address), Name(name), u(b)
  {
  }

  int Address;
  char const *Name;         
  union union_name
  {
    union_name(const TYPE1 &f) : foo(f) {}
    union_name(const TYPE2 &b) : bar(b) {}
    TYPE1 foo;
    TYPE2 bar;
  }u;
};

const PARAMS paramTbl[] {
  PARAMS(0x1000, "Param1", TYPE1("abc", 0)),
};

Full example here

+2
source

All Articles