何时可以使用不强制转换的显式bool操作符?
When can I use explicit operator bool without a cast?
我的类有一个显式的bool转换:
struct T {
explicit operator bool() const { return true; }
};
我有它的一个实例:
T t;
要将其赋值给类型为bool
的变量,我需要编写强制转换:
bool b = static_cast<bool>(t);
bool b = bool(t);
bool b(t); // converting initialiser
bool b{static_cast<bool>(t)};
我知道我可以在没有强制转换的条件中直接使用我的类型,尽管有explicit
限定符:
if (t)
/* statement */;
我还可以在哪里使用t
作为bool
而不强制转换?
标准提到了值可能在上下文中被"转换为bool
"的地方。它们主要分为四组:
语句 if (t) /* statement */;
for (;t;) /* statement */;
while (t) /* statement */;
do { /* block */ } while (t);
表达式 !t
t && t2
t || t2
t ? "true" : "false"
编译时测试 static_assert(t);
noexcept(t)
explicit(t)
if constexpr (t)
if (t) /* statement */;
for (;t;) /* statement */;
while (t) /* statement */;
do { /* block */ } while (t);
!t
t && t2
t || t2
t ? "true" : "false"
static_assert(t);
noexcept(t)
explicit(t)
if constexpr (t)
转换操作符必须为constexpr
。
算法和概念
NullablePointer T
任何地方的标准需要一个类型满足这个概念(例如
std::unique_ptr
的pointer
类型),它可以被上下文转换。此外,NullablePointer
的相等和不等操作符的返回值必须在上下文中转换为bool
。std::remove_if(first, last, [&](auto){ return t; });
在任何具有模板形参
Predicate
或BinaryPredicate
的算法中,谓词实参都可以返回T
。std::sort(first, last, [&](auto){ return t; });
在任何具有模板形参
Compare
的算法中,比较器实参都可以返回T
。
(source1 source2)
请注意const和非const转换操作符的混合使用可能会导致混淆:
- 为什么在上下文转换中不显式bool()转换?
- 为什么
explicit operator bool
没有像预期的那样生效?
相关文章:
- 写入向量<向量<bool>>
- 让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操作符?
- 显式操作符bool未在lambda内部调用- MSVC错误
- 是否可以在类定义之外以某种方式提供操作符bool强制转换的等量物?
- 如何在c++类中重写bool操作符
- 在返回语句中统一初始化,并显式将操作符转换为bool