Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

c++ - When can I use explicit operator bool without a cast?

My class has an explicit conversion to bool:

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

and I have an instance of it:

T t;

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 */;

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Statements

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

Expressions

  •    !t
    
  •    t && t2
    
  •    t || t2
    
  •    t ? "true" : "false"
    

Compile-time tests

  •    static_assert(t);
    
  •    noexcept(t)
    
  •    explicit(t)
    
  •    if constexpr (t)
    

The conversion operator needs to be constexpr for these.

Algorithms and concepts

  •    NullablePointer T
    

    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; });
    

    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; });
    

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

(source1, source2)


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...