C++检测模板化类

Mav*_*ave 7 c++ templates template-meta-programming c++11

template<typename T>
struct check
{
  static const bool value = false;
};
Run Code Online (Sandbox Code Playgroud)

我想要做的是有check<T>::value真当且仅当T是一个std::map<A,B>std::unordered_map<A,B>两者ABstd::string.所以基本上check可以启用类型的编译时检查T.我该怎么做呢?

Xeo*_*Xeo 13

当你想要允许任何比较器,hasher,key-equal-comparator和allocator时的部分特化:

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;
};
Run Code Online (Sandbox Code Playgroud)

如果要检查是否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;
};
Run Code Online (Sandbox Code Playgroud)

如果你想一般检查,如果它是一个std::mapstd::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>>{};
Run Code Online (Sandbox Code Playgroud)