27

Boost.Optional uses a dummy type to allow constructing uninitialized instances of boost::optional<T>. This type is called none_t, and an instance none is already defined in a header for convenience, allowing us to write code such as the following:

boost::optional<int> uninitialized(boost::none);

Looking at the definition of none_t, I noticed that it is in fact a typedef corresponding to a pointer-to-member to some dummy struct:

namespace boost {

namespace detail { struct none_helper{}; }

typedef int detail::none_helper::*none_t ;

none_t const none = (static_cast<none_t>(0)) ;

} // namespace boost

What are the advantages of using such a convoluted typedef over a simple empty struct like this?

namespace boost {

struct none_t {};

none_t const none;

} // namespace boost
Luc Touraille
  • 79,925
  • 15
  • 92
  • 137

1 Answers1

18

Ah, I had never thought to dig deeper.

One (more or less obvious) advantage to a regular struct, is that now none evaluates to false in boolean contexts.

One advantage over another "evaluates to false" is that pointer to member are prevented from harmful promotion to integral types.

So, I guess that it offers a safe and concise way of having a object that evaluates to false.

EDIT: One should recognize here (hum...) the structure of the Safe Bool Idiom.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Ah... `boost::none` indeed converts into `false`. :D – Nawaz Jun 07 '12 at 15:25
  • That makes sense, although I don't really see the point in making `none` convertible to `false`. IMHO, it can only gives the false impression that `none` is an `optional`. But perhaps I am overlooking some corner cases anticipated by the library authors. – Luc Touraille Jun 07 '12 at 15:25
  • 2
    Anyway, in other words, it just follows [Safe Bool Idiom](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool). – Nawaz Jun 07 '12 at 15:26
  • 1
    @LucTouraille: well, I suppose that the same argument could be used against `nullptr`; as they both serve the same role it is somewhat coherent that they behave similarly in many circumstances. – Matthieu M. Jun 07 '12 at 15:27