Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslh_hashoptional
[Package bslh]

Provide hashAppend for std::optional. More...

Namespaces

namespace  bslh

Detailed Description

Outline
Purpose:
Provide hashAppend for std::optional.
Description:
This component provides a free function template, bslh::hashAppend, overloaded for the std::optional class template. Including this function allows for std::optional types (and types that contain them) to be used as keys in BDE hashed containers.
Note that use of this component requires that the language standard be 2017 or later, as that is when std::optional first appears.
Usage:
This section illustrates intended usage of this component.
Example 1: Hashing an optional Boolean value:
Suppose we want to maintain a boolean condition as either true, false, or unspecified, and have it fit within the BDE hash framework. We can use std::optional<bool> for this, and demonstrate that such a value can be correctly hashed.
First, we set up three such optional values to represent the three possible states we wish to represent.
  std::optional<bool> optionalTrue  = true;
  std::optional<bool> optionalFalse = false;
  std::optional<bool> optionalUnset;
Then, we create a hashing object.
  bslh::Hash<> hasher;
Next, we hash each of our values.
  size_t optionalTrueHash  = hasher(optionalTrue);
  size_t optionalFalseHash = hasher(optionalFalse);
  size_t optionalUnsetHash = hasher(optionalUnset);
Then we hash the underlying values.
  size_t expectedTrueHash  = hasher(true);
  size_t expectedFalseHash = hasher(false);
Finally, we verify that the std::optional hasher produces the same results as the underlying hashers. For the disengaged hash, we will just check that the value differs from either engaged value.
  assert(expectedTrueHash  == optionalTrueHash);
  assert(expectedFalseHash == optionalFalseHash);
  assert(expectedTrueHash  != optionalUnsetHash);
  assert(expectedFalseHash != optionalUnsetHash);