2017-05-28 24 views
9

मैं यह जांचना चाहता हूं कि कोई निश्चित टेम्पलेट विशेषज्ञता मौजूद है या नहीं, जहां सामान्य मामला परिभाषित नहीं किया गया है।यह तय कैसे करें कि कोई टेम्पलेट विशेषज्ञता मौजूद है

को देखते हुए:

template <typename T> struct A; // general definition not defined 
template <> struct A<int> {}; // specialization defined for int 

मैं इस तरह एक struct को परिभाषित करना चाहते हैं:

template <typename T> 
struct IsDefined 
{ 
    static const bool value = ???; // true if A<T> exist, false if it does not 
}; 

वहाँ कि (आदर्श सी ++ 11) के बिना करने के लिए एक तरीका है?

धन्यवाद

+1

है क्यों आप ऐसा करने की आवश्यकता होगी? जिज्ञासा से पूछना। – HSchmale

+0

@HSchmale, पूर्ण समस्या का वर्णन यहां दिया गया है: https://stackoverflow.com/questions/44237528/how-to-write-template-overload-functions-with-fallback-triggered-if-template-arg – Fabio

उत्तर

11

तथ्य का उपयोग करना है कि आप एक अधूरी प्रकार के sizeof लागू नहीं कर सकते:

template <class T, std::size_t = sizeof(T)> 
std::true_type is_complete_impl(T *); 

std::false_type is_complete_impl(...); 

template <class T> 
using is_complete = decltype(is_complete_impl(std::declval<T*>())); 

See it live on Coliru


यहाँ एक से थोड़ा भद्दा है, लेकिन काम कर C++ है 03 समाधान:

template <class T> 
char is_complete_impl(char (*)[sizeof(T)]); 

template <class> 
char (&is_complete_impl(...))[2]; 

template <class T> 
struct is_complete { 
    enum { value = sizeof(is_complete_impl<T>(0)) == sizeof(char) }; 
}; 

See it live on Coliru

+0

धन्यवाद। क्या सी ++ 11 के बिना ऐसा करने का कोई तरीका है? – Fabio

+0

@ फ़ैबियो वहां आप जाते हैं। – Quentin

+0

धन्यवाद! क्या C++ 03 समाधान में is_complete_impl की दूसरी परिभाषा में टेम्पलेट आवश्यक है? – Fabio

0

यह वह जगह है एक विकल्प के कार्यान्वयन हमेशा एक ही चाल @Quentin इस्तेमाल किया


सी ++ 11 संस्करण

template<class First, std::size_t> 
using first_t = First; 

template<class T> 
struct is_complete_type: std::false_type {}; 

template<class T> 
struct is_complete_type<first_t<T, sizeof(T)>> : std::true_type {}; 

Example on wandbox


अंतरिम सी + का उपयोग कर +03 संस्करण whi ch काम नहीं करता है

template<typename First, std::size_t> 
struct first { typedef First type; }; 

template<typename T> 
struct is_complete_type { static const bool value = false; }; 

template<typename T> 
struct is_complete_type< typename first<T, sizeof(T)>::type > { static const bool value = true; }; 

त्रुटि इस मामले में

prog.cc:11:8: error: template parameters not deducible in partial specialization: struct is_complete_type< typename first::type > { static const bool value = true; }; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

prog.cc:11:8: note: 'T'

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