Search code examples
c++templatesvariadic-templates

Expand variadic template to array of static members


I've defined a base class template:

template<class actual_class>
class base
{
public:
    static const int value;
}

and the definition of value depends on the actual_class tparam.

Next, I have a bunch of derived classes from base, let's call them a and b. Let's also say that a::value = 5 and b::value = 10.

Now, in a method template where I need to access the static values from a parameter pack. I'd like to have them in a vector.

template<class... derived_from_bases>
void foo(irrelevant_class<derived_from_bases...> irrelevant)
{
    // std::vector<int> values = { ... }
    ...
}

For the function called with < a, b > tparams I'd like the values vector to look like this:

std::vector<int> values = {5 /* a::value */, 10 /* b::value */};

Also having an std::array instead of an std::vector would be a nice touch.

Thank you for your help in advance.


Solution

  • For a vector, you just need

    std::vector<int> values = { derived_from_bases::value... };
    

    If you have C++17, you can get a std::array the same way like

    std::array values = { derived_from_bases::value... };
    

    and CTAD will deduce the type and size of the array for you. If you do not have C++17, then you can use

    std::array<int, sizeof...(derived_from_bases)> values = { derived_from_bases::value... };