【问题标题】:Boost tribool usage提高 tribool 的使用率
【发布时间】:2026-01-30 07:10:02
【问题描述】:

这是我测试 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() 函数将 boost::tribool 转换为纯 bool,但出现编译时错误:

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

【问题讨论】:

    标签: c++ boost tribool


    【解决方案1】:

    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;
      //              ^^^^^^^^
      

      转换运算符意味着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 为假或不确定时为空,因此我们可以将结果视为布尔值。

      【讨论】: