Provide a tag type and constant indicating an empty nullable value.
More...
Namespaces |
namespace | bdlb |
Detailed Description
- Outline
-
-
- Purpose:
- Provide a tag type and constant indicating an empty nullable value.
-
- Classes:
NullOptType | tag type representing an empty nullable value |
nullOpt | literal value of type NullOptType |
- See also:
- Component bdlb_nullablevalue
-
- Description:
- This component provides a class,
bdlb::NullOptType
, that defines a vocabulary to be used in functions that want to indicate an empty nullable value.
- In addition to the
NullOptType
class type, this component defines a constant, bdlb::nullOpt
, of type NullOptType
, to act as a literal of this type, much as nullptr
is a (built in) literal for null pointers.
-
- Usage:
- In this section we show intended use of this component.
-
- Example 1: ...:
- Suppose we are implementing a type that has an optional null (empty) state, such as
NullableValue
. First we declare the class template. namespace xyza {
template <class TYPE>
class NullableValue {
Then, we privide a buffer than can be uninitialized or hold a valid object, and a bool
variable to indicate whether an object is stored in the buffer. Next, we provide a constructor that makes a copy of an argument of the given TYPE
. public:
explicit NullableValue(const TYPE& value);
Then, we provide an implicit constructor using bdlb::NullOptType
to allow our users to explicitly create a nullable object in the null state. Next we provide accessors to indicate whether the object is in the null state, and to return the wrapped value if one is avaialble.
const TYPE& getValue() const;
bool isNull() const;
};
}
Now, we can write a function that consumes a nullable value. namespace xyzb {
struct Utility {
static int unwrap(const xyza::NullableValue<int>& optionalValue);
};
int Utility::unwrap(const xyza::NullableValue<int>& optionalValue) {
if (optionalValue.isNull()) {
return 0;
}
return optionalValue.getValue();
}
}
Finally, our clients can call xyza::Utility::unwrap
with either a nullable value of their own, or with bdlb::nullOpt
to indicate a null object.