1

Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson

class Element : public safe_bool<>
{
public:
    bool Exists() const;
    // boolean_test() is a safe_bool method
    bool boolean_test() const { return Exists(); }; 
};

When I tried to use it in the if expression like below

Element ele;
...
if(ele)

I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error

Element ele;
...
if((bool)ele)

error C2440: 'type cast' : cannot convert from 'Element' to 'bool'

This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!

4

2 回答 2

1

允许使用安全的布尔习语,尽管我通常这样写:

class Element
{
public:
    bool Exists() const;

    /* Begin Safe Bool Idiom */

private:
    // This is a typedef for pointer to an int member of Element.
    typedef int Element::*SafeBoolType;
public:
    inline operator SafeBoolType() const
        { return Exists() ? &Element::someDataMember : 0; }
    inline bool operator!() const
        { return !Exists(); }

    /* End Safe Bool Idiom */

private:
    int someDataMember; // Pick any data member
    // ...
};

这就是我看到它实现的方式。事实上,Boost 以这种方式为智能指针类实现了这种习惯用法(使用包含文件)。

于 2010-12-14T12:54:07.947 回答
0

它似乎不能用任何编译器编译。显然safe_bool不能在其基中返回受保护方法的地址。您应该添加一个公共方法safe_bool_base并返回该方法的地址。

此外,似乎运算符==!=使用非依赖构造禁用(即使未实例化也可能导致错误)。

也许这可以解决问题:

 class safe_bool_base {
  protected:
    typedef void (safe_bool_base::*bool_type)() const;
  private:
    void cannot_compare_boolean_results() const {}
  public:
    void public_func() const {}
  protected:
    safe_bool_base() {}
    safe_bool_base(const safe_bool_base&) {}
    safe_bool_base& operator=(const safe_bool_base&) {return *this;}
    ~safe_bool_base() {}
  };

  template <typename T=void> class safe_bool : public safe_bool_base {
  public:
    operator bool_type() const {
      return (static_cast<const T*>(this))->boolean_test()
        ? &safe_bool_base::public_func : 0;
    }
  protected:
    ~safe_bool() {}
  };

  template<> class safe_bool<void> : public safe_bool_base {
  public:
    operator bool_type() const {
      return boolean_test()==true ? 
        &safe_bool_base::public_func : 0;
    }
  protected:
    virtual bool boolean_test() const=0;
    virtual ~safe_bool() {}
  };

  template <typename T, typename U> 
    bool operator==(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
      lhs.cannot_compare_boolean_results(); //call private method to produce error
      return false;
  }

  template <typename T,typename U> 
  bool operator!=(const safe_bool<T>& lhs,const safe_bool<U>& rhs) {
    lhs.cannot_compare_boolean_results(); //call private method to produce error
    return false;   
  }
于 2010-12-14T12:56:09.490 回答