template<typename T>
struct check
{
static const bool value = false;
};
我想做的是check<T>::value
当且仅当T
is astd::map<A,B>
或std::unordered_map<A,B>
and both A
and B
be时才为真std::string
。所以基本上check
启用了类型的编译时检查T
。我该怎么做呢?
template<typename T>
struct check
{
static const bool value = false;
};
我想做的是check<T>::value
当且仅当T
is astd::map<A,B>
或std::unordered_map<A,B>
and both A
and B
be时才为真std::string
。所以基本上check
启用了类型的编译时检查T
。我该怎么做呢?
当您想要允许任何比较器、哈希器、key-equal-comarator 和分配器时的部分专业化:
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
使用了这些类型的默认版本(又名 onlymap<A,B>
和 not 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
任何键/值组合(以及比较器/哈希器/等)的或,则可以从此处获取完全通用的信息:
#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>>{};
使用部分模板特化
// 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;
};