|
Boost Users : |
From: mr_lilirong_at_[hidden]
Date: 2001-11-22 20:57:33
Thank you very much. Now I understand it.
--- In Boost-Users_at_y..., "Peter Dimov" <pdimov_at_m...> wrote:
> From: <mr_lilirong_at_y...>
> > The following code is excerpted from Boost.Function. I just don't
> > unstanding it. Why use "safe_bool"? What's the advantage? Can any
one
> > explain it to me?
> >
> > Thanks.
> >
> > // code from <boost/function/function_base.hpp>
> > // ===>
> >
> > private:
> > struct dummy {
> > void nonnull() {};
> > };
> >
> > typedef void (dummy::*safe_bool)();
> >
> > public:
> > operator safe_bool () const
> > { return (this->empty())? 0 : &dummy::nonnull; }
>
> safe_bool, as its name implies, is a safer type to use in implicit
> conversions when you need your type to act as a bool, like in
>
> if(f)
>
> Using an operator bool() - since a bool can be converted to int -
means that
> any arithmetic expression that contains 'f' will compile, like
>
> f == 5
> f + 2
> f >> 1
>
> etc
>
> Using 'operator void const * () const', as std::cin and std::cout
do, is a
> bit better, but it still allows some unfortunate side effects:
>
> if(std::cin == std::cout) delete std::cin;
>
> Using a member pointer avoids most of these pitfalls leaving only
> comparisons valid. They are specifically disabled in
boost::function.
>
> --
> Peter Dimov
> Multi Media Ltd.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net