# std::hash <std::experimental::optional>

> C++ Atlas: `cppatlas.com/w/cpp/experimental/optional/hash` | Source: https://en.cppreference.com/w/cpp/experimental/optional/hash | Domain: Technical specifications | Standards: C++11

The template specialization of std::hash for the std::experimental::optional class allows users to obtain hashes of the values contained in optional objects.

## Official Specification Summary (cppreference)

```cpp
// Defined in header <experimental/optional>

template< class T >
struct hash<std::experimental::optional<T>>; // (library fundamentals TS)
```

The template specialization of `std::hash` for the `std::experimental::optional` class allows users to obtain hashes of the values contained in `optional` objects.

### Template parameters

- `T` - the type of the value contained in `optional` object. The specialization `std::hash<T>` must meet the requirements of class template `hash`.

### Example

```cpp
#include <experimental/optional>
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std::literals;

int main()
{
    // hash<optional> makes it possible to use unordered_set
    std::unordered_set<std::experimental::optional<std::string>> s = {
        "abc"s, std::experimental::nullopt, "def"s
    };

    for (const auto& o : s)
        std::cout << o.value_or("(null)") << ' ';
    std::cout << '\n';
}
```

Possible output:

```text
def abc (null)
```

### See also

- [`hash`](https://en.cppreference.com/w/cpp/utility/hash) (C++11): hash function object (class template)

---
Attribution: content from https://en.cppreference.com/w/cpp/experimental/optional/hash (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.