2017-03-08 140 views
1

使用我知道下面的代碼編譯:與可變參數模板

template<class Type> 
class Foo 
{ 
    using type = Type; 
}; 
現在

,我試圖編譯下面的代碼:

template<class Type, class... OtherTypes> 
class Foo 
{ 
    using type = Type; 
    // using types = OtherTypes; 
    // using... types = OtherTypes; 
    // using types... = OtherTypes; 
    // using types = OtherTypes...; 
    // using types... = OtherTypes...; 
}; 

我嘗試了所有的代碼的選項在評論中,但他們都沒有編譯。 我該如何解決它?

+0

你不能。但取決於使用你可以得到替代結構 – bolov

+0

我需要從Foo獲得可變類。就像'Foo :: OtherTypes' –

+1

會像'using types_tuple = std :: tuple '就足夠了嗎? – Caleth

回答

0

您不能將一組類型作爲類中的一個類型。

你可以得到的最接近的大致是:

template<class...Ts> struct types_t { constexpr types_t(){}; }; 
template<class...Ts> constexpr types_t<Ts...> types{}; 

這些值和類型,代表了包的類型。

template<class Type, class... OtherTypes> 
class Foo 
{ 
    using type=Type; 
    using types=types_t<OtherTypes...>; 
}; 

然後我們可以編寫使用捆綁類型並在別處使用它們的幫助函數。

template<template<class...>class Z, class Types> 
struct apply_types;  
template<template<class...>class Z, class...Ts> 
struct apply_types<Z, types_t<Ts...>> { 
    using type=Z<Ts...>; 
}; 

template<template<class...>class Z, class Types> 
using apply_types_t = typename apply_types<Z,Types>::type; 

now apply_types< some_template, some_types_t >獲取包中的類型並將它們傳遞給模板。

0

我們假設你想使用包作爲模板參數。然後你可以嘗試下面的方法。

#include <utility> 

template <class... Types> 
struct Foo {}; 

template <template <class...> class Template, 
      class... Types, 
      template <class...> class T> 
Template<Types...> foo(const T<Types...> &); 

template <template <class...> class Template, class T> 
using Type = decltype(foo<Template>(std::declval<T>())); 

int main() { 
    using T = Foo<int, int>; 

    // As template argument 
    using Tuple = Type<std::tuple, T>; 
    static_assert(std::is_same<Tuple, std::tuple<int, int> >::value, ""); 

    return 0; 
}