2017-03-22 70 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为假或不确定时为空,所以我们可以对结果进行排序,如布尔值。