Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslh_hashvariant
[Package bslh]

Provide hashAppend for std::variant. More...

Namespaces

namespace  bslh

Detailed Description

Outline
Purpose:
Provide hashAppend for std::variant.
Description:
This component provides a free function template, bslh::hashAppend, overloaded for the std::variant class template. Including this function allows for std::variant 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::variant first appears.
Usage:
This section illustrates intended usage of this component.
Example 1: Hashing an integer or floating-point value:
Suppose we want to maintain a value as either an integer or a floating-point number, and have it fit within the BDE hash framework. We can use std::variant<int, double> for this, and demonstrate that such a value can be correctly hashed.
First, we set up a pair of such optional values to represent the two potential states we wish to represent.
  typedef std::variant<int, double> id;
  id variantInt    = 42;
  id variantDouble = 3.475;
Then, we create a hashing object.
  bslh::Hash<> hasher;
Next, we hash each of our values.
  size_t variantIntHash    = hasher(variantInt);
  size_t variantDoubleHash = hasher(variantDouble);
Then we hash the underlying values. A variant hashes as a pair of values, first the size_t index of the held type, then the contained value, so we need to accumulate the hashes.
  bslh::Hash<>::HashAlgorithm haInt;
  hashAppend(haInt, size_t(0));
  hashAppend(haInt, 42);
  size_t expectedIntHash = size_t(haInt.computeHash());

  bslh::Hash<>::HashAlgorithm haDouble;
  hashAppend(haDouble, size_t(1));
  hashAppend(haDouble, 3.475);
  size_t expectedDoubleHash = size_t(haDouble.computeHash());
Finally, we verify that the std::variant hasher produces the same results as the underlying hashers.
  assert(expectedIntHash    == variantIntHash);
  assert(expectedDoubleHash == variantDoubleHash);