否定标准::integral_constant<bool>
negation of std::integral_constant<bool>
很抱歉问这么简单的问题,但我不容易找到答案。谷歌对"C++否定integral_constant"和类似的查询没有任何有趣的说法。
在C++11中是否有任何特征使std::true_type
从std::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_type
和false_type
类型都有一个引用自身的嵌套 typedef,因此您可以编写:
std::is_same<my_static_bool::type,std::false_type>::value
根据上下文,只做!my_static_bool{}
可能更简单,如果你的类型确实是std::false_type
,这是一个价值constexpr
true
。
相关文章:
- 写入向量<向量<bool>>
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 让bool方法返回其他整数
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- Arduino-C++ bool 不会从 false 变为 true
- 为什么在这种情况下,bool 类型的输出等于 0?
- 显式 std::exception_ptr 转换为 bool 不存在.VS2010 错误?
- 错误:不能使用"显式"说明符声明 bool'
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- 从标准::字符串到标准::矢量<bool>的快速转换
- 为什么 bool 和 _Bool 如果它们在内存中占用 1 个字节,它们只能存储 0 或 1
- 通过 mpi 发送 c++ 标准::矢量<bool>
- 为什么使用Pool和Bool而不是int8_t或char
- 如何为地图< map<int,int> 、bool > 分配值?
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- 使用 bool 和 const char 重载的 C++ 函数会在没有警告的情况下产生歧义 (MSVC2012)
- 返回 bool 作为 CPP 中 bool 运算符 [] 中的值