2013-09-25 30 views
4

數量說我有一個被另外的整體POD類型參數化的類型:元組任意的,但編譯時已知的類型

template< size_t N > 
struct MyFoo { /* ... */ }; 

有了它,就可以讓他們的元組:

typedef std::tuple< MyFoo<1>, MyFoo<2>, MyFoo<3> > Foo3; 

但現在,我想有一種 「Foo<N>」,其中Nconstexpr。一種實現類似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.... */ 

E.e.爲我想要的每個N手動專門化。有沒有更通用的方法來做到這一點?

謝謝:)

回答

2
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

+0

不錯!有沒有辦法做到這與變量模板?我有點卡在舊標準... – Sh4pe

+0

@ Sh4pe,Boost在該領域有一些支持。 – chris

+1

@ Sh4pe如果你不能使用C++ 11,那麼你必須按照你已經做的或者使用預處理宏的方式來完成它。 – Simple

3

你需要一些機械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; 
}; 

Live demo.

+0

很酷,我以爲'Foo(bar)...'只能和函數一起工作。 – chris

+1

C++ 14有這個機器,順便說一句。 –

+0

不錯!有沒有辦法做到這與變量模板?我有點卡住了舊標準... – Sh4pe

相關問題