5

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

bar is inside a union u. I am unable to initialize it this way. Compiler is unable to resolve bar in ctor parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.