[英]Tuple of an arbitrary, but compile-time-known number of types
假設我有一個由另一個整數POD類型參數化的類型:
template< size_t N >
struct MyFoo { /* ... */ };
有了它,它可以有一個元組:
typedef std::tuple< MyFoo< 1 >, MyFoo< 2 >, MyFoo< 3 > > Foo3;
但現在,我希望有一個類型“ Foo< N >
”,其中N
是constexpr
。 實現類似Foo< N >
一種方法是:
template< size_t N >
struct Foos;
template<> struct Foos< 1 >{ typedef std::tuple< MyFoo< 1 > > type; };
template<> struct Foos< 2 >{ typedef std::tuple< MyFoo< 1 >, MyFoo< 2 > > type; };
/* continue with this.... */
Ee專門為每個NI想要專門化它。 有沒有更通用的方法來做到這一點?
謝謝 :)
你需要一些機器來構建從1到N的整數序列。其余的非常簡單:
#include <cstddef>
#include <tuple>
// to generate a sequence of indices:
template<size_t... Ns>
struct indices {
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template<size_t N>
struct make_indices {
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 > {
typedef indices<> type;
};
// create a sequence and expand it inside a typedef
template<size_t N>
struct MyFoo {};
template< size_t N >
struct Foos {
template<typename>
struct Helper;
template<size_t... Ns>
struct Helper<indices<Ns...>> {
typedef std::tuple< MyFoo<Ns>... > type;
};
typedef typename
Helper< typename make_indices<N>::type >::type type;
};
template<std::size_t N, std::size_t... Is>
struct MakeFoos : MakeFoos<N - 1, N, Is...>
{
};
template<std::size_t... Is>
struct MakeFoos<0, Is...>
{
using type = std::tuple<MyFoo<Is>...>;
};
template<std::size_t N>
struct Foos
{
using type = typename MakeFoos<N>::type;
};
讓你的元組寫Foos<3>::type
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.