|
Boost : |
From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-10-10 11:22:40
On Wednesday 10 October 2001 10:55, you wrote:
> A problem with the precise definition of such a cast is when is the
> returned pointer/reference invalidated.
I would think we'd follow the lead of the std containers here: don't specify
in the cast function itself when the pointer/refefence is invalidated, but
instead specify in the documentation of the variant-like type when references
can be invalidated. For instance, std::vector<T, A>::begin() doesn't specify
when the iterator becomes invalid, but std::vector<T, A>::reserve() specifies
that it may invalidate all pointers, references, and iterators to contained
data.
> Whether this is acceptable depends on the point of view; is boost::function
> merely an useful third party library or something that is aimed at std::?
Both?
> You can't even think of getting such a specification standardized. :-)
>
> I suggest something like:
>
> typedef <implementation-defined> bool_type; // convertible to bool
>
> operator bool_type() const;
>
> // no operator! in the specification, as it is a workaround.
Fair enough.
> > safe_bool should go into utility.hpp, and then it would have
> > documentation
>
> so
>
> > this problem would be avoided. I promised to do that but haven't yet
> > delivered :(.
>
> Actually I don't think that this would be a good idea. A 'standard'
> safe_bool will enable comparisons between unrelated types.
True. I'm considering proposing two additional class templates for
operators.hpp: one that allows conversion to bool (bool_convertable) by
supplying a safe_bool type (that will be unique for each bool_convertable
type), an appropriate safe_bool-creation function, and operator! for broken
compilers; the second class template poisons the comparison operators == and
!=. Code for the classes follows, and the use of them together is quite
simple:
class function_base :
public bool_convertable<function_base>,
public not_equality_comparable<function_base>
{
public:
operator safe_bool() const { return make_safe_bool(!empty()); }
// ...
}
// -- Possible extension proposal for operators.hpp
template<typename T>
class bool_convertable {
struct dummy {
void nonnull() {};
};
protected:
typedef void (dummy::*safe_bool)();
static safe_bool make_safe_bool(bool p)
{ return p? &dummy::nonnull : 0; }
// Only needed for some broken compilers
friend safe_bool operator!(const T& t)
{ return make_safe_bool(!((bool)t)); }
};
template<typename T, typanem U = T>
struct not_equality_comparable {
friend void operator==(const T&, const U&);
friend void operator!=(const T&, const U&);
};
Doug
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk