Azmisov Azmisov - 2 months ago 12
C++ Question

C++ template method to specialize union types

Suppose I have a union:

union U{
int i;
float f;

I want to write a generic method that uses it as a float or int. Something like this:

template <typename T>
T sum(std::vector<U> vec){
T res(0);
for (U &v: vec){
res += ... // use v.i or v.f depending on what T is
return res;

Is there a way to do this? This was just an example method. I have a much longer, complicated method, and I don't want to duplicate it just to switch which union type it is using.


Specialization would work:

template <typename T> T const & get(U const &);

template <> int const & get<int>(U const & u) { return u.i; }
template <> float const & get<float>(U const & u) { return u.f; }


for (U & v : vec) { res += get<T>(v); }