c++ convert class to boolean

前端 未结 5 1349
既然无缘
既然无缘 2020-12-14 16:12

With all of the fundamental types of C++, one can simply query:

if(varname)

and the type is converted to a boolean for evaluation. Is there

5条回答
  •  悲&欢浪女
    2020-12-14 16:44

    As others have stated, using operator int () or operator bool () is bad idea because of the conversions it allows. Using a pointer is better idea. The best know solution to this problem so far is to return a member (function) pointer:

    class MyClass {
      void some_function () {}
    
      typedef void (MyClass:: * safe_bool_type) ();
      operator safe_bool_type () const
      { return cond ? &MyClass::some_function : 0; }
    };
    

提交回复
热议问题