检索递归可变参数模板的特殊类型参数

Retrieve special type parameter of recursive variadic template

有可能吗:

#include <iostream>
#include <string>

template<typename T1, typename T2, typename T3, typename T4, class ...Ts>
struct third_t {

    typedef typename third_t<T2,T3,T4,Ts...>::type type;
};

template<typename T1,typename T2, typename T3>
struct third_t<T1,T2,T3,void> {

    typedef T3 type;
};

int main() {

    third_t<int,int,std::string,unsigned>::type z = "test";

    std::cout<<"string type: "<<z<<std::endl;
}

如果是,为什么找不到特例? IE。决议中甚至没有考虑它。

我收到错误:

main.cpp: In instantiation of 'struct third_t<int, int, std::__cxx11::basic_string<char>, unsigned int>':

main.cpp:18:46:   required from here

main.cpp:7:56: error: wrong number of template arguments (3, should be at least 4)

     typedef typename third_t<T2,T3,T4,Ts...>::type type;

更新:

我意识到我最初的错误假设让我认为我也可以 "overload" 和 class,这当然是无稽之谈。而类似的事情可以用函数模板来完成,那

template<typename T1,typename T2, typename T3>
struct third_t { ... };

无法使用 class 模板完成,如果可以的话,可以从模板参数中提取第三个 最后一个 参数。

why isn't the specialized case found?

因为

的类型列表末尾没有void
third_t<int,int,std::string,unsigned>::type z = "test";

如果你尝试

third_t<int,unsigned,int,std::string,void>::type z = "test";

编译。

-- 编辑--

OP 要求使用 "recorsive construction".

获得第三种类型

所以我建议构造一个类型特征,它获得类型列表的第 n 个类型(其中 n 是模板参数)。

类似

template <std::size_t N, typename, typename ... Ts>
struct nth_t
 { using type = typename nth_t<N-1U, Ts...>::type; };

template <typename T0, typename ... Ts>
struct nth_t<0U, T0, Ts...>
 { using type = T0; };

所以第三个参数可以使用索引2U找到(和C/C++一样,从0U开始)如下

nth_t<2U, int, int, std::string, void>::type z = "test";