3
std::vector<std::type_index> vec;

template <typename T1, typename... Tn>
void Fill() {
    vec.push_back(typeid(T1));
    // fill the vector with the remaining type ids
}

I want to fill the vector with the typeids of the template arguments. How could I implement this?

Appleshell
  • 7,088
  • 6
  • 47
  • 96
  • This question may be related to your problem: [**Creating an array initializer from a tuple or variadic template parameters**](http://stackoverflow.com/questions/18251815/creating-an-array-initializer-from-a-tuple-or-variadic-template-parameters). Note that the templated parameters are evaluated at compile time. – πάντα ῥεῖ May 02 '14 at 13:52

3 Answers3

10

The following solution uses intializer list:

template <typename... Types>
void Fill(std::vector<std::type_index>& vec)
{
    vec.insert(vec.end(), {typeid(Types)...});
}

See live example.

Constructor
  • 7,273
  • 2
  • 24
  • 66
4

This should work:

template<typename T>
void Fill() {
    vec.push_back(typeid(T));
}

template <typename T1, typename T2, typename... Tn>
void Fill() {
    Fill<T1>();
    Fill<T2, Tn...>();
}

Live example

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
2

Implement it using recursion:

std::vector<std::type_index> vec;

template<typename T>
void fill(){
    vec.emplace_back(typeid(T)); // pretty sure you want emplace_back here ;)
}

template<typename T1, typename T2, typename ... Tn>
void fill(){
    fill<T1>();
    fill<T2, Tn...>();
}

I think this will do what you want.

RamblingMad
  • 5,332
  • 2
  • 24
  • 48