Boost logo

Boost :

Subject: Re: [boost] safe-bool CRTP class
From: Jeffrey Lee Hellrung, Jr. (jeffrey.hellrung_at_[hidden])
Date: 2011-05-27 14:55:10


On Fri, May 27, 2011 at 9:52 AM, Christian Holmquist
<c.holmquist_at_[hidden]>wrote:

> On 27 May 2011 11:28, Stewart, Robert <Robert.Stewart_at_[hidden]> wrote:
>
> > Krzysztof Czainski wrote:
> > >
> > > Vladimir Batov prepared a safebool helper class as part of his
> > > Pimpl library.
> > [snip]
> >
> >
> There exists a safebool in already accepted Boost.Log:
>
> http://boost-log.svn.sourceforge.net/viewvc/boost-log/trunk/boost-log/boost/log/utility/explicit_operator_bool.hpp?revision=601&view=markup
>

I'll chime in for my vote of something more along the lines of Andrey's
nullary macro design, except using a pointer-to-member-variable rather than
a pointer-to-member-function to address MSVC efficiency concerns (see prior
post by S.T. Lavavej). I use something like the following, which I had also
picked up from Andrey in a past boost-dev list post.

#define BOOST_EXPLICIT_BOOL() \
private: \
    struct _boost_explicit_bool_struct \
    { int _dummy; int member; }; \
    typedef int (_boost_explicit_bool_struct::*_boost_bool_type); \
public: \
    operator _boost_bool_type() const { return !*this ? 0 :
&_boost_explicit_bool_struct::member; }

When BOOST_NO_EXPLICIT_CONVERSION_OPERATORS is not defined, then the above
macro is defined to just declare an explicit bool conversion, so it amounts
to the same framework you would use in C++0x.

I prefer a macro solution over a CRTP solution because 1) it retains
POD'ness (in C++03, at least; I believe the definition of POD has been
extended in C++0x...?); and 2) the macro appears in the same place one would
otherwise declare a bool conversion operator.

I also like the solution to use operator! by default in the implementation
of the explicit bool conversion operator; perhaps a second macro could be
provided to allow one to specify the specific expression (e.g., "!!*this" or
"as_bool()") one should use.

- Jeff


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