BDE 4.14.0 Production release
|
Macros | |
#define | bsls_UnspecifiedBool bsls::UnspecifiedBool |
This alias is defined for backward compatibility. | |
Provide a class supporting the unspecified bool
idiom.
unspecified bool
idiom.This component provides a class template that can be used to manufacture an "unspecified boolean type" that is distinct for each class that instantiates it. Note that classes supplying an implicit conversion to an unspecified bool type will be equality comparable (using operator==
and operator!=
) through this conversion. Private equality and inequality operators should be added to the class definition unless this comparison is desired. It is important that each class produces a distinct unspecified bool type, as otherwise objects of different class types would compare equal through this same conversion.
This component will become redundant when all Bloomberg production compilers support "explicit conversion operators", a feature of C++11. An explicit operator bool()
conversion operator is superior to this C++98 idiom in all ways.
This section illustrates intended use of this component.
A common requirement for "smart pointer" types is to emulate the native pointer types and, in particular, support testing for "null" or "empty" pointer values as a simple boolean conversion in if
and while
clauses. We here demonstrate how to create a simple smart pointer type, SimplePtr
, using this component to implement a safe the boolean conversion.
An object of type SimplePtr
holds a pointer value, but does not claim ownership or any responsibility for the lifetime of the referenced object. A SimplePtr
object acts as a "simple" native pointer.
First, we create the SimplePtr
class, define its data members, creators and manipulators:
Next, we define, for convenience, an alias for a unique type that is implicitly convertible to bool
(note that we pass the current template instantiation to the bsls::UnspecifiedBool
template to guarantee a unique name, even for different instantiations of this same SimplePtr
template):
Now, we can define a boolean conversion operator that tests whether or not this SimplePtr
object is holding a null pointer, or a valid address:
Note that we do not need to define operator!
as this single boolean conversion operator is invoked with the correct semantics when the user tries that operator.
Finally, we write a simple test function, creating a couple of SimplePtr
objects, one "null", and the other with a well-defined address.
Notice that SimplePtr
objects behave as native pointers. They should be tested before dereferencing (as they could be null).
#define bsls_UnspecifiedBool bsls::UnspecifiedBool |