The Safe Bool Idiom学习

找到原作者的连接,很多代码无法执行,以下是修改后,在vs2015下运行通过的代码: 

/*
The Safe Bool Idiom
by Bjorn Karlsson
https://www.artima.com/cppsource/safebool3.html
*/
class safe_bool_base {
public:
    void this_type_does_not_support_comparisons() const {}
protected:
    typedef void (safe_bool_base::*bool_type)() const;  // define class const member pointer
    
    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 { // 重載返回基類const 成員指針類型
        return (static_cast<const T*>(this))->boolean_test() ?
            &safe_bool_base::this_type_does_not_support_comparisons : 0;

    }
protected:
    ~safe_bool() {}
};

template<> class safe_bool<void> : public safe_bool_base { // 對 void 類型進行特化
public:
    operator bool_type() const {
        return boolean_test() == true ?
            &safe_bool_base::this_type_does_not_support_comparisons : 0;
    }
protected:
    virtual bool boolean_test() const = 0;
    virtual ~safe_bool() {}
};


template <typename T, typename U> // 錯誤處理, 禁止 == 操作
void operator==(const safe_bool<T>& lhs, const safe_bool<U>& rhs) {
    lhs.this_type_does_not_support_comparisons();
    return false;
}

template <typename T, typename U> // 錯誤處理  禁止 != 操作 
void operator!=(const safe_bool<T>& lhs, const safe_bool<U>& rhs) {
    lhs.this_type_does_not_support_comparisons();
    return false;
}

// use  派生类必须实现 boolean_test 函数
class Testable_without_virtual : private safe_bool<Testable_without_virtual> {
public:

    //在此处使用using,目的:告知编译器,当前类使用safe_bool重载后的 bool_type,而不是引用基类bool_type类型的定义。
    using safe_bool<Testable_without_virtual>::operator bool_type;
    bool boolean_test() const {
        return true;
    }
};

测试: 


 

// 
    Testable_without_virtual twv, twv2;
    if (twv)
    {
        std::cout << "twv:" << std::endl;
    }
    std::cout << "safe bool test: " << i << std::endl;

    if (twv == twv2) {}
    if(twv != twv2){}

猜你喜欢

转载自blog.csdn.net/kasteluo/article/details/82019330