否定标准::integral_constant<bool>

negation of std::integral_constant<bool>

本文关键字:lt bool gt 标准 integral constant      更新时间:2023-10-16

很抱歉问这么简单的问题,但我不容易找到答案。谷歌对"C++否定integral_constant"和类似的查询没有任何有趣的说法。

在C++11中是否有任何特征使std::true_typestd::false_type中产生,反之亦然?换句话说,我想要一些更易读的版本

std::is_same<my_static_bool, std::false_type>

我当然知道我可以自己写,但如果有的话,我想使用现有的。

没有,因为它本质上是单行代码,<type_traits>应该尽可能小。

template <typename T> using static_not = std::integral_constant<bool, !T::value>;

用法:

static_not<my_static_bool>

这是正确的方法,因为标准总是说"false_type或派生自这样",所以你不能依赖等于std::false_type。我通常将其放宽为"具有 constexpr 布尔::value属性",因为我不使用标签调度。

另一种方法:

template <typename T>
using static_not = typename std::conditional<
    T::value,
    std::false_type,
    std::true_type
>::type;

下面的代码使用模板元函数转发(即它继承自具有否定布尔值的std::integral_constant,这当然是受到大量使用此模式的 Boost.MPL 的启发(

#include <type_traits>
template<typename T>
struct logical_not
:
    std::integral_constant<bool, !T::value>
{};
int main()
{
   typedef logical_not<std::false_type>::type T;
   typedef logical_not<std::true_type>::type F;
   static_assert((std::is_same<T, std::true_type>::value), "");
   static_assert((std::is_same<F, std::false_type>::value), "");   
}

实时工作空间上的输出

true_typefalse_type类型都有一个引用自身的嵌套 typedef,因此您可以编写:

std::is_same<my_static_bool::type,std::false_type>::value

根据上下文,只做!my_static_bool{}可能更简单,如果你的类型确实是std::false_type,这是一个价值constexpr true