Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

struct

I want to port a look-up table of parameters which is an array of structures in C to C++. I read a few questions and understood that the C-style struct 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.

like image 983
OnkarK Avatar asked Oct 31 '22 02:10

OnkarK


1 Answers

You can have a struct/union constructor to initialize with 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)),
};

Complete example here

like image 153
Mohit Jain Avatar answered Nov 15 '22 04:11

Mohit Jain