Search code examples
c++c++20c++-templates

How can I make variable amount of types in union using templates in C++


I want to store variable amount of types in union in my structure. For example

template <typename ...Args> // (Arg1, Arg2, Arg3, ... Argn)
struct Foo {
  union {
    Arg1 val1;
    Arg2 val2;
    Arg3 val3;
    ....
    
    Argn valn;
  };
};

I have no idea. How can I make this possible using templates in C++20?


Solution

  • If you're looking for a tagged union, then you don't need to write such template, because the standard library comes with one: std::variant.

    But to answer more generally: You cannot expand a parameter pack into data member declarations. What you can do, is expand the pack into a template argument list. As such, we can define a class (in this case a union class) that nests all the parameters in members of members using recursion:

    template <typename ...Args>
    union var_union {};
    
    template <typename First, typename ...Rest>
    union var_union<First, Rest...> {
        First first;
        var_union<Rest...> rest;
    };