【问题标题】:C++ detect templated classC++ 检测模板类
【发布时间】:2012-10-16 16:30:10
【问题描述】:
template<typename T>
struct check
{
  static const bool value = false;
};

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

【问题讨论】:

    标签: c++ templates c++11 template-meta-programming


    【解决方案1】:

    当您想要允许任何比较器、哈希器、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 是否使用了这些类型的默认版本(也就是只有 map&lt;A,B&gt; 而不是 map&lt;A,B,my_comp&gt;,您可以省略模板参数并使用显式特化:

    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,您可以完全通用,取自here

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

    【讨论】:

      【解决方案2】:

      使用部分模板特化

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-13
        • 2014-03-31
        相关资源
        最近更新 更多