Search code examples
c++templatesc++11variadic-templatestypeinfo

How to obtain the types in a C++11 parameter pack?


I'm not sure that I worded the question in the most effective way, but I'm just now starting to use C++11 and am having trouble applying its new features to the problem at hand. I have the following notional function:

template <typename ... Args>
std::vector<std::type_index> foo()

I would like foo() to return a vector that contains a type_index value for each of the types in the parameter pack Args. For example, foo<int, vector<int>, double>() would return a vector containing { type_index(typeid(int)), type_index(typeid(vector<int>)), type_index(typeid(double)) }.

Notionally, I would like to iterate over the types in the pack and invoke the above transform on each of them (i.e. given a type T, return type_index(typeid(T)). I feel like there should be a clean way to accomplish this, but it's not clear to me how to operate the variadic template machinery to make this work. Is my intuition correct?


Solution

  • The simplest way to "iterate" over types in a pack is to use pack expansion to repeat the desired pattern. In this case you'd write something like the following:

    return { type_index(typeid(Args))... }