Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ send arguments to union (variable union)

Tags:

c++

c++11

well i cant find how do this, basically its a variable union with params, basic idea, (writed as function)

Ex1

union Some (int le)
{
  int i[le];
  float f[le];
};

Ex2

union Some
{
  int le;
  int i[le];
  float f[le];
};

obs this don't works D: maybe a way to use an internal variable to set the lenght but don't works too. Thx.

like image 794
Latot Avatar asked May 16 '26 01:05

Latot


1 Answers

No, this is not possible: le would need to be known at compile-time.

One solution would be to use a templated union:

template <int N> union Some
{
    int i[N];
    float f[N];
};

N, of course, is compile-time evaluable.

Another solution is the arguably more succinct

 typedef std::vector<std::pair<int, float>> Some;

or a similar solution based on std::array.

like image 171
Bathsheba Avatar answered May 17 '26 14:05

Bathsheba