Boost logo

Boost :

From: Isaac Dupree (isaacdupree_at_[hidden])
Date: 2008-08-10 10:35:12


I'm looking at all these "operator unspecified_bool_type"s
in Boost. They vary:

It's hard to get all of these right, and various Boost
libraries have made changes in the past that got it wrong:
type-safety
compiler workarounds
zero runtime overhead (a.k.a. more compiler workarounds)

In fact I haven't previously seen an implementation that
obviously achieves safety in the general case. Even
pointer-to-members have an operator== and operator!=, which
will cause trouble if the boolean-convertible type doesn't
have its own operator== and operator!= (although it often
does). But it is possible! I thought it required macros at
first, but it actually works better(in some ways) with the
Curiously Recurring Template Pattern.
If you, the user, make a class C (such as shared_ptr) that
you want to have an operator safe-bool,
derive from a boost::convertible_to_bool<C> (and define a
member of C "bool operator_bool() const"). Boost shall
have, in order to generate errors for invalid operations,
the following:
template<typename
T>operator==(boost::convertible_to_bool<T>const&,
boost::unspecified_bool_type);
template<typename T>operator==(boost::unspecified_bool_type,
boost::convertible_to_bool<T>const&);
and similar for operator!=, and (when unspecified_bool_type
is a function pointer) for <, >, <=, >=.
(The return type is something clever like
boost::TYPES_MAY_NOT_BE_COMPARED_IMPLICITLY_VIA_BOOLEAN_CONVERSIONS
to improve error messages.)

When the compiler has support for the C++0x "explicit
operator bool", none of these hacks are needed, and the
library can adjust to that too.

There are several more details I've been looking at too...
ADL, base-chaining like Boost.Operators, writing tests/docs
for weird inheritance situations... :-)

Perhaps this should be provided as a Boost library in its
own right, and Boost should use it everywhere that Boost
currently uses idiosyncratic operator safe-bools. Are there
any pitfalls I'm missing? (are there important compilers
that can't deal with the overhead or correctness of using a
base class for this purpose?) Does this sound like a good
idea? I can post my code soon if there's interest.

-Isaac


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