我什么时候可以使用显式运算符bool而无需强制转换?

时间:2016-10-12 09:49:03

标签: c++ implicit-conversion

我的班级明确转换为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吗?

1 个答案:

答案 0 :(得分:35)

标准提到值可能&#34; 从上下文转换为bool &#34; 的地方。它们分为四大类:

  • 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
    

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

  • bool

    在任何名为std::remove_if(first, last, [&](auto){ return t; }); Predicate的模板参数的算法中,谓词参数都可以返回BinaryPredicate

  • T
    在具有名为std::sort(first, last, [&](auto){ return t; }); 的模板参数的任何算法中,比较器参数可以返回Compare

source1source2

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

相关问题