Azmisov - 4 months ago 18

C++ Question

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.

Answer Source

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; }
```

Usage:

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