【问题标题】:When can I use explicit operator bool without a cast?什么时候可以在没有强制转换的情况下使用显式运算符 bool?
【发布时间】:2017-02-21 01:50:30
【问题描述】:

我的班级有一个明确的布尔转换:

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 而无需演员?

【问题讨论】:

    标签: c++ implicit-conversion


    【解决方案1】:

    标准提到了值可能在上下文中转换为bool的地方。它们分为四大类:

    声明

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

    表达式

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

    编译时测试

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

    对于这些,转换运算符需要为constexpr

    算法和概念

    •    NullablePointer T
      

      标准需要满足此概念的类型(例如std::unique_ptrpointer 类型)的任何地方,都可以根据上下文进行转换。此外,NullablePointer 的等式和不等式运算符的返回值必须可根据上下文转换为bool

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

      在任何带有名为PredicateBinaryPredicate 的模板参数的算法中,谓词参数都可以返回T

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

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

    (source1, source2)


    请注意,混合使用 const 和非常量转换运算符可能会造成混淆:

    【讨论】:

      猜你喜欢
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多