2012-10-16 12 views
6
template<typename T> 
struct check 
{ 
    static const bool value = false; 
}; 

मुझे क्या करना चाहते हैं check<T>::value सच हो यदि और केवल यदि T एक std::map<A,B> या std::unordered_map<A,B> और दोनों A और Bstd::string होना है है। तो मूल रूप से checkT प्रकार की संकलन-समय की जांच को सक्षम बनाता है। मैं यह कैसे कर सकता हूं?सी टेम्प्लेटेड वर्ग का पता लगाने के ++

उत्तर

11

जब आप किसी भी तुलनित्र, क़मी बनाने की मशीन, की-बराबर-तुलनित्र और संभाजक अनुमति देना चाहते हैं के लिए आंशिक विशेषज्ञता:

template<class Comp, class Alloc> 
struct check<std::map<std::string, std::string, Comp, Alloc>>{ 
    static const bool value = true; 
}; 

template<class Hash, class KeyEq, class Alloc> 
struct check<std::unordered_map<std::string, std::string, Hash, KeyEq, Alloc>>{ 
    static const bool value = true; 
}; 

आप अगर जाँच करना चाहते हैं T ने उन प्रकारों के डिफ़ॉल्ट संस्करण का उपयोग किया (उर्फ केवल map<A,B> और map<A,B,my_comp> नहीं, आप टेम्पलेट तर्क छोड़ सकते हैं और स्पष्ट विशेषज्ञता के साथ जा सकते हैं:

template<> 
struct check<std::map<std::string, std::string>>{ 
    static const bool value = true; 
}; 

template<> 
struct check<std::unordered_map<std::string, std::string>>{ 
    static const bool value = true; 
}; 

और आप आम तौर पर जांच करने के लिए अगर यह एक std::map या किसी कुंजी/मान संयोजन के std::unordered_map (और तुलनित्र/क़मी बनाने की मशीन/आदि) है चाहते हैं तो आपको here से पूरी तरह से सामान्य रूप में लिया जाना कर सकते हैं:

#include <type_traits> 

template < template <typename...> class Template, typename T > 
struct is_specialization_of : std::false_type {}; 

template < template <typename...> class Template, typename... Args > 
struct is_specialization_of< Template, Template<Args...> > : std::true_type {}; 

template<class A, class B> 
struct or_ : std::integral_constant<bool, A::value || B::value>{}; 

template<class T> 
struct check 
    : or_<is_specialization_of<std::map, T>, 
     is_specialization_of<std::unordered_map, T>>{}; 
3

उपयोग कुछ आंशिक टेम्पलेट विशेषज्ञता

// no type passes the check 
template< typename T > 
struct check 
{ 
    static const bool value = false; 
}; 

// unless is a map 
template< typename Compare, typename Allocator > 
struct check< std::map< std::string, std::string, Compare, Allocator > > 
{ 
    static const bool value = true; 
}; 

// or an unordered map 
template< typename Hash, typename KeyEqual, typename Allocator > 
struct check< std::unordered_map< std::string, std::string, Hash, KeyEqual, Allocator > > 
{ 
    static const bool value = true; 
}; 
संबंधित मुद्दे