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

我想做的是check<T>::value当且仅当Tis astd::map<A,B>std::unordered_map<A,B>and both Aand Bbe时才为真std::string。所以基本上check启用了类型的编译时检查T。我该怎么做呢?

4

2 回答 2

13

当您想要允许任何比较器、哈希器、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::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>>{};
于 2012-10-16T16:35:56.773 回答
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;
};
于 2012-10-16T16:34:41.243 回答