C++检测模板化类

C++ detect templated class

本文关键字:检测 C++      更新时间:2023-10-16
template<typename T>
struct check
{
  static const bool value = false;
};

我想做的是让check<T>::value成为真的,当且仅当Tstd::map<A,B>std::unordered_map<A,B>并且AB都是std::string。所以基本上check启用类型T的编译时检查。我该怎么做?

当您想要允许任何比较器、哈希器、键相等比较器和分配器时,部分专用化:

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

使用一些部分模板专用化

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