Boost logo

Boost :

From: Daniel Frey (d.frey_at_[hidden])
Date: 2003-03-08 02:32:40


On Fri, 07 Mar 2003 11:46:24 +0100, Sam Partington wrote:

> Hate to sound pushy, but I've no answer on this, were the patches ok?

>> >> Daniel Frey wrote:
>> > No problem. IIRC it was Peter Dimov who came up with the safe-bool
>> > idiom first. At least I saw it first from him. Another way which
>> > works but results in worse error messages is this:
>> >
>> > template <class T, class B = ::boost::detail::empty_base> struct
>> > bool_testable : B
>> > {
>> > private:
>> > operator int() const;
>> >
>> > public:
>> > operator bool() const
>> > {
>> > return !!static_cast< T& >( *this );
>> > }
>> > };

One problem I just found with your implementation (and thus with Peter's
idiom in general) is, that is doesn't provide an operator bool(). This
may sound weird, an example hopefully clears things up:

#include <iostream>
using namespace std;

#include <boost/operators.hpp>

struct A : boost::bool_testable< A >
{
    bool operator!() const { cout << "operator!" << endl; return false; }
    operator int() const { cout << "operator int()" << endl; return 42; }
};

int main()
{
    A a;
    if( a )
        cout << "Hello, world!" << endl;
    // int i = a;
    // long l = a;
}

The code above happily compiles without warnings but it calls operator
int(). Several options come to mind:

- Document it that the class T of bool_testable< T > shall not have any
other operators that might conflict.
- Use the above alternative implementation I showed. It is not as nice as
yours/Peter's wrt error-messages, but it works as expected.
- Convince the standard committee that "explicit operator bool" is needed
:) See: http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&frame=right&th=d0969f0fa2460dd4&seekm=3A2D10EE.35544D0A%40aixigo.de#link1

Thoughts?

Regards, Daniel


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