用户自定义bool转换的优先级

Precedence of user-defined bool conversion

我有一个围绕句柄的包装器(表示为 int),只要句柄本身可用,它就应该可用。但我也想在 if 条件下轻松检查。 -1 or <0 是无效值。我的想法:

#include <cassert>

struct Foo{
    int i;
    Foo(int i): i(i){}
    operator int() const { return i; }
    operator bool() const { return i >= 0; }
};

int main(){
    Foo a(0);
    if(a)
        ;
    else
        assert(false);
    if(!a)
        assert(false);
    assert(!!a);
    Foo b(1);
    assert(!!b);
    assert(b);
    assert(a != b);
    Foo c(-1);
    Foo d(-1);
    assert(!c);
    assert(c==d);
    Foo e(-2);
    assert(c!=e);
}

这样我可以轻松地将 Foo 传递给采用 int 的函数,并且所有检查都通过。但是我担心 int 转换优先于 bool 转换。有没有?我可以确定 if(Foo(...))/if(!Foo(...))/if(!!Foo(...)) 总是采用 bool 转换,而直接比较采用 int 转换,因此 Foo(1) != Foo(0)Foo(1) != Foo(2) 总是给出?

标准 (C++98) 似乎没有对 bool/int 用户定义的转换下订单。

Can I be sure, that if(Foo(...))/if(!Foo(...))/if(!!Foo(...)) always takes the bool conversion

是的。 operator! 和 if 语句的条件要求将表达式转换为 bool。通过 int 的转换需要用户定义的到 int 的转换,然后是到 bool 的标准转换。直接转换为 bool 只需要一个用户定义的转换。一个(后一个)转换优于两个(前一个)转换。

while direct comparisons take the int conversion so that Foo(1) != Foo(0) and Foo(1) != Foo(2) is always given?

没有。两种转换的排名相同,并且其意图不明确。不明确的转换使程序格式错误。

解决方案:要么定义 operator==(const Foo&, const Foo&)operator!=(const Foo&, const Foo&),要么在比较之前显式转换。