2013-04-28 8 views
5

विफल रहा है मैं एक ट्यूपल के अंतिम तत्व को हटाने का प्रयास कर रहा हूं। यह तब काम करता है जब मेरे पास हटाने के लिए टुपल में केवल एक तत्व होता है। लेकिन जब मेरे पास एक से अधिक होते हैं, तो चीजें गलत होती हैं। मुझे नहीं मिल रहा है कि यह क्यों काम नहीं कर रहा है। इन त्रुटियों को मैं हो रही हैं:टुपल से अंतिम प्रकार को हटाने का प्रयास

prog.cpp: In function ‘ int main() ’:
prog.cpp:24:22: error: incomplete type ‘ remove_last<std::tuple<int, int> > ’ used in nested name specifier
prog.cpp:24:22: error: incomplete type ‘ remove_last<std::tuple<int, int> > ’ used in nested name specifier
prog.cpp:24:70: error: template argument 1 is invalid

#include <tuple> 
#include <type_traits> 

template <class T> 
struct remove_last; 

template <class T> 
struct remove_last<std::tuple<T>> 
{ 
    using type = std::tuple<>; 
}; 

template <class... Args, typename T> 
struct remove_last<std::tuple<Args..., T>> 
{ 
    using type = std::tuple<Args...>; 
}; 

int main() 
{ 
    std::tuple<int, int> var; 

    static_assert(
     std::is_same<remove_last<decltype(var)>::type, 
     std::tuple<int>>::value, "Values are not the same" 
    ); 
} 

त्रुटियों चले जाओ जब मैं विशेषज्ञताओं में से एक में टेम्पलेट तर्क गैर variadic बनाते हैं। लेकिन फिर यह एक विशेषज्ञता बन जाती है जो केवल दो तत्वों के साथ एक ट्यूपल को संसाधित करेगी - न कि जो मैं लक्ष्य रख रहा था। विविध तर्कों के साथ मैं इसे कैसे प्राप्त कर सकता हूं? दूसरे शब्दों में, टुपल में एक से अधिक तत्व होने पर मैं इसे कैसे काम कर सकता हूं?

उत्तर

5

समस्या यह है कि तर्क पैक लालची है और - क्योंकि यह पहली बार आता है - T सहित टाइप कटौती करते समय अनुक्रम में सभी प्रकारों को खाता है, आपको Args... से बाहर रहने की उम्मीद है। इस तरह से

template <class T, class... Args> 
struct remove_last<std::tuple<T, Args...>> 
{ 
    using type = typename concat_tuple< 
     std::tuple<T>, 
     typename remove_last<std::tuple<Args...>>::type 
     >::type; 
}; 

और है concat_tuple मेटा-समारोह में परिभाषित किया गया:

template<typename, typename> 
struct concat_tuple { }; 

template<typename... Ts, typename... Us> 
struct concat_tuple<std::tuple<Ts...>, std::tuple<Us...>> 
{ 
    using type = std::tuple<Ts..., Us...>; 
}; 

आप variadic विशेषज्ञता इस तरह से परिभाषित करते हैं (सूचना है कि तर्क पैक अब std::tuple<T, Args...>आखिरी में दिखाई दे रहा है) कर सकता है

+0

मुझे यह जवाब नहीं समझा। क्यों * "तर्क पैक लालची है" * 'concat_tuple' के विशेषज्ञता पर लागू नहीं होता है? – Nawaz

+0

@ नवाज: क्योंकि 'concat_tuples' के प्रकार के तर्कों की संख्या –

+0

तय की गई है, मैं रिकर्सिव भाग को समझ नहीं पा रहा हूं। क्या आप मुझे समझा सकते हैं कि यह अंतिम तत्व को कैसे हटा रहा है? – 0x499602D2

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