你可以避免使用类似的结构 typeList 索引可变参数类型
struct noTypeInList
{ };
template <std::size_t, typename ...>
struct typeSel;
template <typename T0, typename ... Ts>
struct typeSel<0U, T0, Ts...>
{ using type = T0; };
template <std::size_t N, typename T0, typename ... Ts>
struct typeSel<N, T0, Ts...>
{ using type = typename typeSel<N-1U, Ts...>::type; };
template <std::size_t N>
struct typeSel<N>
{ using type = noTypeInList; };
所以
std::make_unique< TypeList<Types...>::T1 > ();
成为
std::make_unique< typeSel<0, Types...>::type > ();
以下是完整的 C++11 示例,以防您想要 std::tuple 或 std:unique_ptr
#include <tuple>
#include <memory>
struct noTypeInList
{ };
template <std::size_t, typename ...>
struct typeSel;
template <typename T0, typename ... Ts>
struct typeSel<0U, T0, Ts...>
{ using type = T0; };
template <std::size_t N, typename T0, typename ... Ts>
struct typeSel<N, T0, Ts...>
{ using type = typename typeSel<N-1U, Ts...>::type; };
template <std::size_t N>
struct typeSel<N>
{ using type = noTypeInList; };
template <std::size_t ...>
struct range
{ };
template <std::size_t N, std::size_t ... Next>
struct rangeH
{ using type = typename rangeH<N-1U, N-1U, Next ... >::type; };
template <std::size_t ... Next >
struct rangeH<0U, Next ... >
{ using type = range<Next ... >; };
template<typename... Types>
class Application
{
private:
std::tuple<std::unique_ptr<Types>...> tpl;
template <std::size_t ... rng>
Application (const range<rng...> &)
: tpl{std::make_tuple(std::unique_ptr<
typename typeSel<rng, Types...>::type>()...)}
{ }
public:
Application () : Application(typename rangeH<sizeof...(Types)>::type())
{ }
};
int main()
{
Application<int, float, int, std::tuple<double, long>> a;
}
这只是typeSel 的使用示例,因为Application 可以简单地写成
template<typename... Types>
class Application
{
private:
std::tuple<std::unique_ptr<Types>...> tpl;
public:
Application () : tpl{std::make_tuple(std::unique_ptr<Types>()...)}
{ }
};
如果你可以使用C++14编译器,你可以使用std::index_sequence和std::make_index_sequence(并删除range和rangeH)和Application可以变成
template<typename... Types>
class Application
{
private:
std::tuple<std::unique_ptr<Types>...> tpl;
template <std::size_t ... rng>
Application (const std::index_sequence<rng...> &)
: tpl{std::make_tuple(std::unique_ptr<
typename typeSel<rng, Types...>::type>()...)}
{ }
public:
Application () : Application(std::make_index_sequence<sizeof...(Types)>())
{ }
};