C++中是否有“普通”的一元逻辑运算符?

3

我们都知道有一个否定逻辑运算符!,可以这样使用:

class Foo
{
public:
    bool operator!() { /* implementation */ }
};

int main()
{
    Foo f;
    if (!f)
        // Do Something
}

有没有任何运算符可以实现这个:

if (f)
    // Do Something

我知道这可能不重要,但只是好奇!


通过定义运算符 bool(),您可以得到您想要的结果。 - maress
@maress:是的,我们已经涉及到了那个问题。 - Lightness Races in Orbit
可能是http://www.artima.com/cppsource/safebool.html的重复。 - Lightness Races in Orbit
3个回答

7
你可以声明和定义operator bool(),以便进行隐式转换为bool,但是需要小心谨慎
或者写成:
if (!!f)
   // Do something

我知道我可以这样做,但是没有直接的运算符吗? - Tamer Shlash
1
@Mr.TAMER:operator bool() 怎么不是直接的? - Lightness Races in Orbit
1
@Mr.TAMER:if需要其条件表达式为bool类型,因此您提供的任何内容都将在可能的情况下转换为bool。对于if (1)也是同样的情况。 - Lightness Races in Orbit
1
明白了,谢谢 :),但是你说的“小心”是什么意思?我应该更加关注什么? - Tamer Shlash
1
@Mr.TAMER:谷歌搜索“安全的bool习惯用法”(http://www.google.co.uk/search?ix=icb&sourceid=chrome&ie=UTF-8&q=safe+bool+idiom)。 - Oliver Charlesworth

3

由于operator bool()本身相当危险,我们通常使用一个叫做安全布尔Idiom的东西:

class X{
  typedef void (X::*safe_bool)() const;
  void safe_bool_true() const{}
  bool internal_test() const;
public:
  operator safe_bool() const{
    if(internal_test())
      return &X::safe_bool_true;
    return 0;
  }
};

在C++11中,我们得到了显式转换运算符;因此,上述惯用法已经过时
class X{
  bool internal_test() const;
public:
  explicit operator bool() const{
    return internal_test();
  }
};

2
operator bool() { //implementation };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接