Namespaces
Variants

std:: hash <std::optional>

From cppreference.net
Utilities library
定义于头文件 <optional>
template < class T >
struct hash < std:: optional < T >> ;
(C++17 起)

针对 std::optional 类的 std::hash 模板特化允许用户获取 optional 对象所含值的哈希值。

当且仅当 std:: hash < std:: remove_const_t < T >> 启用时(参见 std::hash ),特化模板 std::hash < std:: optional < T >> 才会被启用,否则该特化将被禁用。

当启用时,对于包含值的 std:: optional < T > 类型对象 o std::hash < std:: optional < T >> ( ) ( o ) 的计算结果与 std:: hash < std:: remove_const_t < T >> ( ) ( * o ) 相同。对于不包含值的 optional 对象,其哈希值是未指定的。

此特化的成员函数不保证为 noexcept,因为底层类型的哈希操作可能抛出异常。

模板参数

T - optional 对象中所含值的类型

示例

#include <iostream>
#include <optional>
#include <string>
#include <unordered_set>
using namespace std::literals;
int main()
{
    using OptStr = std::optional<std::string>;
    // hash<optional> 使得可以使用 unordered_set
    std::unordered_set<OptStr> s =
    {
        "ABC"s, "abc"s, std::nullopt, "def"s
    };
    for (const auto& o : s)
        std::cout << o.value_or("(null)") << '\t' << std::hash<OptStr>{}(o) << '\n';
}

可能的输出:

def     11697390762615875584
(null)  18446744073709548283
abc     3663726644998027833
ABC     11746482041453314842

参见

(C++11)
哈希函数对象
(类模板)