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

我想要做的是有check<T>::value是真实的,当且仅当Tstd::map<A,B>std::unordered_map<A,B>两者ABstd::string。所以基本上check启用编译时检查类型T。 我该怎么做?c + +检测模板类

回答

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; 
};