mardi 6 septembre 2022

Is there any alternative of using union in C++, if data type of variable is not specified

So, I have json file which has some parameters defining the name, value and type. for e.g., { name: "something", type: "uint32_t", value: 12 }

and I am creating struct mapping of this json parameter, it looks like

enum some_enum{en_int8, en_int16, ....};
struct{
  std::string name; // Name of parameter
  some_enum type;   // type of parameter
  union{
    uint8_t var1;
    uint16_t var2;
    ..... //all other requried types
  }
}

As I don't know about the type of parameter coming from file, I am creating this union for storing value and using enum to access the specified value.

I think this is c-style way to do it.

So, I want to ask, is there any alternative way, rather than of using union for creating mapping like this in C++/Modern C++. Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire