繁体   English   中英

C ++检测模板化类

[英]C++ detect templated class

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

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

当你想要允许任何比较器,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;
};

如果你想检查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 (以及比较器/ hasher /等),你可以从这里获得完全通用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM