2017-03-22 49 views
1

這是我的測試提振的樣本:: tribool:升壓tribool使用

#include <iostream> 
#include "boost/logic/tribool.hpp" 

int main() 
{ 
boost::logic::tribool init; 
//init = boost::logic::indeterminate; 
init = true; 
//init = false; 

if (boost::logic::indeterminate(init)) 
{ 
    std::cout << "indeterminate -> " << std::boolalpha << init << std::endl; 
} 
else if (init) 
{ 
    std::cout << "true -> " << std::boolalpha << init << std::endl; 
} 
else if (!init) 
{ 
    std::cout << "false -> " << std::boolalpha << init << std::endl; 
} 

bool safe = init.safe_bool(); <<---- error here 
if (safe) std::cout << std::boolalpha << safe << std::endl; 

return 0; 
} 

我想使用safe_bool()函數的boost :: tribool轉換爲純布爾,但有請編譯時錯誤:

Error 1 error C2274 : 'function-style cast' : illegal as right side of '.' operator D : \install\libs\boost\boost_samples\modules\tribool\src\main.cpp 23 1 tribool 

看起來我錯誤地使用了safe_bool()函數。 你能幫我解決這個問題嗎?謝謝。

回答

2

safe_bool是一種類型,即函數operator safe_bool()tribool轉換爲safe_bool。如果你只是將什麼轉換成常規bool使用:bool safe = init;safe在這種情況下將是true當且僅當init.value == boost::logic::tribool::true_value

2

safe_bool "method"不是一個正常的方法,而是一個conversion operator

BOOST_CONSTEXPR operator safe_bool() const noexcept; 
//    ^^^^^^^^ 

轉換操作符是指當請求中boolean值tribool將被用作一個bool,所以你只需要編寫:

bool safe = init; // no need to call anything, just let the conversion happen. 

// or just: 
if (init) { ... } 

你應該注意到的是,操作員返回safe_bool ,而不是boolsafe_bool這裏實際上是一個內部成員函數指針類型:

class tribool 
{ 
private: 
    /// INTERNAL ONLY 
    struct dummy { 
    void nonnull() {}; 
    }; 

    typedef void (dummy::*safe_bool)(); 

它是這樣寫的以下的safe bool idiomwhich is obsolete in C++11)。

重要的是當tribool爲真時指針非空,而tribool爲假或不確定時爲空,所以我們可以對結果進行排序,如布爾值。