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

objdef anobj();
if(anobj){
  //initialize check is true
}else{
  //cannot use object right now
}

不仅用于初始化,还用于检查其使用能力。

最佳答案

istream 的做法是提供对 void* 的隐式转换

  • http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/
  • stream output and implicit void* cast operator function invocation

  • 更新 根据评论,Safe Bool Idiom 将是一个更好的解决方案:(直接代码 taken from that page )
      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;
        }
    

    Bjorn Karlsson 的文章包含一个 reusable implementation 用于 Safe Bool Idiom



    旧样本:

    为了享受,我仍然展示了 operator 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;
    }
    

    关于c++ - 如何在 C++ 中创建一个类,初始化时,在调用其名称时返回一个 bool 值,但没有显式函数调用 make,如 ifstream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7446079/

    10-11 22:33
    查看更多