2013-03-14 6 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

+0

मुझे इस चाल को सीखने की ज़रूरत है। +1 – jrok

+0

+1: कॉम्पैक्ट और सुरुचिपूर्ण –

0

आप std::tuple_element का उपयोग कर एक टपल प्रकार के तत्वों के प्रकार का उपयोग कर सकते हैं। यह वास्तव में आपको ट्यूपल तत्व प्रकारों को प्रतिस्थापित करने की अनुमति नहीं देता है, लेकिन यह आपको टुपल प्रकारों को अन्य प्रकार के प्रकारों में तत्व प्रकारों के रूप में उपयोग किए जाने वाले प्रकारों के संदर्भ में परिभाषित करने की अनुमति देता है।

संबंधित मुद्दे