How to deploy custom templates

I am trying to get the type at the specified index in a parameter package using template metaprogramming. I have the code below, but for some reason it always returns int, can someone tell me what I'm 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 above code should return stringas a type for a, but somehow it is alwaysint

+4
source share
2 answers
TypeForIndex<2, int, double, string>

ok, pattern matching time. First, it clearly matches

template <int current_index, typename... Vs>
struct TypeForIndex {};

therefore no errors. Does this fit any other specialization?

AND:

template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...>

AT:

template <int current_index, typename Tail>
struct TypeForIndex<current_index, Tail>

Well, this corresponds to (A), not (B).

(A), current_index - 2, Head - int, Tail... - double, std::string.

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

private TypeForIndex<current_index + 1> . , , , . , .

template <int current_index, typename Head, typename... Tail>
struct TypeForIndex<current_index, Head, Tail...> {
    using type = Head;
};

, Head int. , type=int.

. type int.

...

, ? (.. , ), , , , . current_index+1 - , , , .

, , :

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

type, .

size_t a int.

+7

.

#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...> : TypeForIndex<current_index - 1, Tail...> {};

template <typename Head, typename... Tail>
struct TypeForIndex<0, Head, Tail...> {
    using type = Head;
};

int main() {
    TypeForIndex <2, int, double, string, char>::type a ("hello");
    cout << a << endl;
}
+2

All Articles