When can I use explicit operator bool without a cast?

后端 未结 1 896
梦谈多话
梦谈多话 2020-12-03 02:50

My class has an explicit conversion to bool:

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

and I have an instance of it

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 02:58

    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

    The operator needs to be constexpr for these:

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

    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:

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

    0 讨论(0)
提交回复
热议问题