c – 我什么时候可以使用显式操作符bool而不使用强制转换?
作者:互联网
我的班级明确转换为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)};
我知道我可以直接在没有强制转换的条件中使用我的类型,尽管有明确的限定符:
if (t)
/* statement */;
我还能在没有演员的情况下使用t作为布尔?
解决方法:
该标准提到了值可能“在上下文中转换为bool”的位置.它们分为四大类:
声明
>
if (t) /* statement */;
>
for (;t;) /* statement */;
>
while (t) /* statement */;
>
do { /* block */ } while (t);
表达式
>
!t
>
t && t2
>
t || t2
>
t ? "true" : "false"
编译时测试
操作符需要为这些:constexpr:
>
static_assert(t);
>
noexcept(t)
>
if constexpr (t)
算法和概念
>
NullablePointer T
标准要求满足此概念的类型(例如std :: unique_ptr的指针类型)的任何地方都可以进行上下文转换.此外,NullablePointer的相等和不等式运算符的返回值必须在上下文中可转换为bool.
>
std::remove_if(first, last, [&](auto){ return t; });
在具有名为Predicate或BinaryPredicate的模板参数的任何算法中,谓词参数可以返回T.
>
std::sort(first, last, [&](auto){ return t; });
在任何带有名为Compare的模板参数的算法中,比较器参数都可以返回T.
请注意,const和非const转换运算符的混合可能会导致混淆:
> Why doesn’t explicit bool() conversion happen in contextual conversion?
> Why does the explicit operator bool
not in effect as expected?
标签:c,implicit-conversion 来源: https://codeday.me/bug/20191004/1853182.html