Boost logo

Boost :

Subject: Re: [boost] safe bool not safe enough ?
From: John Maddock (boost.regex_at_[hidden])
Date: 2013-03-14 09:54:29


>> class Testable
>> {
>> bool ok_;
>> typedef void (Testable::*bool_type)() const;
>> void this_type_does_not_support_**comparisons() const {}
>> public:
>> explicit Testable(bool b=true):ok_(b) {}
>>
>> operator bool_type() const
>> {
>> return ok_==true ?
>> &Testable::this_type_does_not_**support_comparisons : 0;
>> }
>> };
>>
>> Testable t(true);
>>
>> bool b = t; // Compiles OK - Ooops!
>>
>
> I'm curious, why is this bad? I personally hate the fact, that the above
> doesn't compile for explicit operator bool(), which leads to idioms like
> !!t.

It's bad because the type isn't logically convertible to bool, BTW the !!t
idiom isn't required in C++11 mode, the following works just fine:

#include <iostream>

class Testable
{
   bool ok_;
   typedef void (Testable::*bool_type)() const;
   void this_type_does_not_support_comparisons() const {}
public:
   explicit Testable(bool b=true):ok_(b) {}

   explicit operator bool() const
   {
      return ok_;
   }
};

int main()
{
   Testable t(true);

   if(t) std::cout << "Yeh\n";

   if(!t) std::cout << "Oh\n";

   bool b = t ? true : false;

   return 0;
}

John.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk