3

That is my sample of testing 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;
}

I am trying to use safe_bool() function to convert boost::tribool to plain bool but have complile time error:

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

Looks like i am using safe_bool() function incorrectly. Could you help me resolve this issue? Thanks.

Space Rabbit
  • 141
  • 2
  • 11

2 Answers2

3

safe_bool is a type, i.e., the function operator safe_bool() converts a tribool to a safe_bool. If you simply what to convert to a regular bool use: bool safe = init;. safe will in this case be true if and only if init.value == boost::logic::tribool::true_value.

Jonas
  • 6,915
  • 8
  • 35
  • 53
2

That safe_bool "method" is not a normal method, but a conversion operator.

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

The conversion operator means the tribool will act like a bool when a boolean is requested, so you just need to write:

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

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

You should notice that the operator returns a safe_bool, not a bool. safe_bool here is actually an internal member-function-pointer type:

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

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

It is written like this following the safe bool idiom (which is obsolete in C++11).

What is important it that the pointer is non-null when the tribool is true, and null when the tribool is false or indeterminate, so we could sort-of treat the result like a boolean.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005