C++ 提高tribool的使用率

C++ 提高tribool的使用率,c++,boost,tribool,C++,Boost,Tribool,这是我测试boost::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

这是我测试boost::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()函数。 你能帮我解决这个问题吗?谢谢。

这不是一种正常的方法,而是一种很好的方法

转换运算符意味着当请求布尔值时,
tribool
将像
bool
一样工作,因此您只需编写:

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

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

您应该注意到,运算符返回的是
安全布尔
,而不是
布尔
<代码>安全布尔这里实际上是一个内部成员函数指针类型:

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

  typedef void (dummy::*safe_bool)();
它是这样写的,如下所示()


重要的是,当
tribool
为真时指针为非空,当
tribool
为假或不确定时指针为空,因此我们可以将结果视为布尔值。

safe\u bool
是一种类型,即函数
运算符safe\u bool()
tribool
转换为
safe\u bool
。如果您只需要将什么转换为常规的
bool
使用:
boolsafe=init<在这种情况下,当且仅当
init.value==boost::logic::tribool::true_value
时,code>safe
将为
true

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

// or just:
if (init) { ... }
class tribool
{
private:
  /// INTERNAL ONLY
  struct dummy {
    void nonnull() {};
  };

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