如何在C++中创建一个类,在初始化时,在调用其名称时返回一个布尔值,但没有显式函数调用make,如ifstream

Jos*_*osh 3 c++ class

如何在C++中创建一个类,在初始化时,在调用其名称时返回一个布尔值,但没有显式函数调用make,如ifstream.我希望能够这样做:

objdef anobj();
if(anobj){
  //initialize check is true
}else{
  //cannot use object right now
}
Run Code Online (Sandbox Code Playgroud)

不只是初始化,而是检查其使用能力.

seh*_*ehe 5

的方式istream做它是通过提供隐式转换void*

更新为了回应评论,Safe Bool Idiom将是一个更好的解决方案:( 直接从该页面获取的代码)

  class Testable {
    bool ok_;
    typedef void (Testable::*bool_type)() const;
    void this_type_does_not_support_comparisons() const {}
  public:
    explicit Testable(bool b=true):ok_(b) {}

    operator bool_type() const {
      return ok_==true ? 
        &Testable::this_type_does_not_support_comparisons : 0;
    }
  };

  template <typename T> 
    bool operator!=(const Testable& lhs,const T& rhs) {
    lhs.this_type_does_not_support_comparisons();   
      return false; 
    } 
  template <typename T>
    bool operator==(const Testable& lhs,const T& rhs) {
    lhs.this_type_does_not_support_comparisons();
      return false;     
    }
Run Code Online (Sandbox Code Playgroud)

Bjorn Karlsson的文章包含了Safe Bool Idiom 的可重用实现


旧样本:

为了享受,我仍然展示了操作员void*重载的直接实现,为了清晰起见并且还显示了问题:

#include <iostream>

struct myclass
{
     bool m_isOk;

     myclass() : m_isOk(true) { }
     operator void* () const { return (void*) (m_isOk? 0x1 : 0x0); }
};

myclass instance;

int main()
{
    if (instance)
        std::cout << "Ok" << std::endl;

    // the trouble with this:
    delete instance; // no compile error !
    return 0;
}
Run Code Online (Sandbox Code Playgroud)