我想使用模板元編程在參數包中的指定索引處獲取類型。我有下面的代碼,但由於某種原因它總是返回一個int
,有人可以告訴我我做錯了什麼嗎?如何展開模板專門化
#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;
}
上述代碼應返回string
作爲a
的類型,但不知它始終是一個int
上面的僅僅是一個固定,只要更換'TypeForIndex <2,整型,雙,字符串> :: type'用'string'是一個修正:HTTP://coliru.stacked-crooked。com/a/d2876707b8677e26 - 它返回正確的類型,但不正確。在鏈接中,我在包的最後添加了一個'char'類型,並且代碼無法編譯。 – Yakk
是的。我編輯他的代碼直到編譯完成。我沒有意識到他犯了更多的錯誤。我在代碼中添加了缺少的「尾部...」。 – prestokeys
@prestokeys謝謝你的回答!你的意見對我來說同樣重要,但我會繼續接受Yakk的回答,因爲它有更好的解釋。雖然我贊成15分! – Curious