【问题标题】:How to combine conditions from type_traits the standard way如何以标准方式组合来自 type_traits 的条件
【发布时间】:2015-09-11 07:50:54
【问题描述】:

例如,只有当 std::is_pointer<T>std::is_const<T> 评估为 true_type 时,我才想使用类型 T

当然,有这样一个简单的方法:

template <typename T>
void f(T t, std::true_type, std::true_type) {}
template <typename T>
void f(T t)
{
  f(t, std::is_pointer<T>{}, std::is_const<T>{});
}

但我想要这样的东西:

template <typename T>
void f(T t, std::true_type) {}
template <typename T>
void f(T t)
{
  f(t, std::and<std::is_pointer<T>, std::is_const<T>>{});
}

标准库是否包含类似std::and 的内容?如果没有,是否有一种简单的方法来实现所需的功能?

【问题讨论】:

    标签: c++ c++11 templates typetraits


    【解决方案1】:

    你可以简单地&amp;&amp; 把traits 的结果放在一起,然后放到std::integral_constant 中:

    std::integral_constant<bool, 
                           std::is_pointer<T>::value && std::is_const<T>::value>
    

    或者你可以写一个通用特征and。来自here的一些可能性:

    选项 1

    template<typename... Conds>
      struct and_
      : std::true_type
      { };
    
    template<typename Cond, typename... Conds>
      struct and_<Cond, Conds...>
      : std::conditional<Cond::value, and_<Conds...>, std::false_type>::type
      { };
    
    //usage
    and_<std::is_pointer<T>, std::is_const<T>>
    

    选项 2

    template<bool...> struct bool_pack;
    template<bool... bs> 
    using and_ = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>;
    
    //usage
    and_<std::is_pointer<T>, std::is_const<T>>
    

    当我们收到fold expressions 时,您将能够这样做:

    template<typename... Args>
    using and_ = std::integral_constant<bool, (Args::value && ...) >;
    

    您的编译器可能已经在 -std=c++1z 标志下支持此功能,例如 this

    【讨论】:

      【解决方案2】:

      随着 C++17 conjunctiondisjunction 的出现,您可以轻松地编写可变参数(数量)谓词:

      template <class T, template <class> class... Ps>
      constexpr bool satisfies_all_v = std::conjunction<Ps<T>...>::value;
      
      template <class T, template <class> class... Ps>
      constexpr bool satisfies_any_v = std::disjunction<Ps<T>...>::value;
      

      这就是你使用它的方式:

      satisfies_all_v<T, is_pointer, is_const>
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2019-02-28
        • 2016-09-21
        相关资源
        最近更新 更多