Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rationale for boost::none_t implementation?

Tags:

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 
like image 732
Luc Touraille Avatar asked Jun 07 '12 15:06

Luc Touraille


People also ask

When to use boost:: optional?

boost::optional It is recommended to use optional in situations where there is exactly one, clear (to all parties) reason for having no value of type T, and where the lack of value is as natural as having any regular value of T.

How do I know if Boost optional is set?

With is_initialized() you can check whether an object of type boost::optional is not empty. Boost. Optional speaks about initialized and uninitialized objects – hence, the name of the member function is_initialized() . The member function get() is equivalent to operator* .

What is Boost optional?

Boost C++ Libraries Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers.


1 Answers

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.

like image 62
Matthieu M. Avatar answered Oct 21 '22 15:10

Matthieu M.