dimanche 27 mars 2016

How to unroll template specializations

I am trying to get the type at the specified index in a parameter pack using template metaprogramming. I have the code below but for some reason it always returns an int, could someone tell me what I am doing wrong?

#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;

template <int current_index, typename... Vs>
struct TypeForIndex {};
template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...> : private TypeForIndex<current_index + 1> {
    using type = Head;
};
template <int current_index, typename Tail>
struct TypeForIndex<current_index, Tail> {
    using type = Tail;
};

int main() {

    TypeForIndex <2, int, double, string>::type a {"hello"};
    cout << a << endl;

    return 0;
}

The code above should return string as the type for a but somehow it is always an int

Aucun commentaire:

Enregistrer un commentaire