2013-03-14 55 views
9

有沒有辦法替換元組元素編譯時間如何在編譯時替換元組元素?

例如,

using a_t = std::tuple<std::string,unsigned>; // start with some n-tuple 
using b_t = element_replace<a_t,1,double>;  // std::tuple<std::string,double> 
using c_t = element_replace<b_t,0,char>;  // std::tuple<char,double> 

回答

17

您可以使用此:

// the usual helpers (BTW: I wish these would be standardized!!) 
template< std::size_t... Ns > 
struct indices 
{ 
    typedef indices< Ns..., sizeof...(Ns) > next; 
}; 

template< std::size_t N > 
struct make_indices 
{ 
    typedef typename make_indices< N - 1 >::type::next type; 
}; 

template<> 
struct make_indices<0> 
{ 
    typedef indices<> type; 
}; 

// and now we use them 
template< typename Tuple, std::size_t N, typename T, 
      typename Indices = typename make_indices< std::tuple_size<Tuple>::value >::type > 
struct element_replace; 

template< typename... Ts, std::size_t N, typename T, std::size_t... Ns > 
struct element_replace< std::tuple<Ts...>, N, T, indices<Ns...> > 
{ 
    typedef std::tuple< typename std::conditional< Ns == N, T, Ts >::type... > type; 
}; 

,然後用它是這樣的:

using a_t = std::tuple<std::string,unsigned>;  // start with some n-tuple 
using b_t = element_replace<a_t,1,double>::type; // std::tuple<std::string,double> 
using c_t = element_replace<b_t,0,char>::type; // std::tuple<char,double> 
+3

指數。 ♥♥♥♥♥♥ – Xeo 2013-03-14 14:31:46

+0

我需要學習這個技巧。 +1 – jrok 2013-03-14 14:32:38

+0

+1:緊湊而優雅 – 2013-03-14 14:32:58

0

您可以訪問類型使用std::tuple_element元組類型的元素。這實際上並不允許您替換元組元素類型,但它允許您根據在其他元組類型中用作元素類型的類型定義元組類型。