From:
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
// ===> 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.