I’m dealing with an union in C++, and I would like have a function template which access to the active union member depending on a template parameter.
Code is something like (doSomething is just an example):
union Union {
int16_t i16;
int32_t i32;
};
enum class ActiveMember {
I16
, I32
}
template <ActiveMember M>
void doSomething(Union a, const Union b) {
selectMemeber(a, M) = selectMember(b, M);
// this would be exactly (not equivalent) the same
// that a.X = b.X depending on T.
}
To accomplish this I only found bad hacks like specialization, or a not homogeneous way to access and assign.
I’m missing something, and such things should be do it with other approach?
Possibility 1
instead of using an enum, you can use simple structs to pick the member:
This requires to define a struct and a selectMember method for every member in the union, but at least you can use selectMember across many other functions.
Note that I turned the arguments to references, you might adjust this if not appropriate.
Possibility 2
By casting the union pointer to the desired type pointer, you can go with a single selectMember function.