什么时候可以不使用强制转换而使用显式运算符bool? [英] When can I use explicit operator bool without a cast?

查看:81
本文介绍了什么时候可以不使用强制转换而使用显式运算符bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级有向bool的显式转换:

My class has an explicit conversion to bool:

struct T {
    explicit operator bool() const { return true; }
};

我有一个实例:

T t;

将其分配给类型为 bool ,我需要编写一个强制转换:

To assign it to a variable of type bool, I need to write a cast:

bool b = static_cast<bool>(t);
bool b = bool(t);
bool b(t);  // converting initialiser
bool b{static_cast<bool>(t)};

我知道我可以在没有强制转换的条件下直接使用我的类型,尽管显式限定词:

I know that I can use my type directly in a conditional without a cast, despite the explicit qualifier:

if (t)
    /* statement */;

在哪里可以使用 t 作为 bool 没有强制转换?

Where else can I use t as a bool without a cast?

推荐答案

该标准提到了值所在的地方可能会 上下文转换为 bool 。它们分为四个主要类别:

The standard mentions places where a value may be "contextually converted to bool". They fall into four main groups:


if (t) /* statement */;


  • for (;t;) /* statement */;
    


  • while (t) /* statement */;
    


  • do { /* block */ } while (t);
    



    !t
    


  • t && t2
    


  • t || t2
    


  • t ? "true" : "false"
    


  • 对于这些操作员,必须为 constexpr

    The operator needs to be constexpr for these:


    static_assert(t);
    


  • noexcept(t)
    


  • if constexpr (t)
    



    NullablePointer T
    

    在标准要求满足该概念的任何类型的任何地方(例如, std :: unique_ptr pointer 类型),进行上下文转换。另外, NullablePointer 的相等和不相等运算符的返回值必须在上下文中可转换为 bool

    Anywhere the Standard requires a type satisfying this concept (e.g. the pointer type of a std::unique_ptr), it may be contextually converted. Also, the return value of a NullablePointer's equality and inequality operators must be contextually convertible to bool.

    std::remove_if(first, last, [&](auto){ return t; });
    

    在任何模板参数为 Predicate 或 BinaryPredicate ,谓词参数可以返回 T

    In any algorithm with a template parameter called Predicate or BinaryPredicate, the predicate argument can return a T.

    std::sort(first, last, [&](auto){ return t; });
    



    在任何模板参数为 Compare 的算法中,比较器参数可以返回 T

    In any algorithm with a template parameter called Compare, the comparator argument can return a T.

    source1 source2

    请注意,const和非const转换运算符的混合使用会引起混淆:

    Do be aware that a mix of const and non-const conversion operators can cause confusion:

    • Why doesn't explicit bool() conversion happen in contextual conversion?
    • Why does the explicit operator bool not in effect as expected?

    这篇关于什么时候可以不使用强制转换而使用显式运算符bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆