Namespaces
Variants

std:: hash <std::optional>

From cppreference.net
Utilities library
헤더에 정의됨 <optional>
template < class T >
struct hash < std:: optional < T >> ;
(C++17부터)

std::hash std::optional 클래스에 대한 템플릿 특수화는 사용자가 optional 객체에 포함된 값들의 해시를 얻을 수 있도록 합니다.

특수화 std::hash < std:: optional < T >> 는 활성화됩니다 (참조 std::hash ) 만약 std:: hash < std:: remove_const_t < 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)
해시 함수 객체
(클래스 템플릿)