1
2// Copyright 2020 Peter Dimov.
3// Distributed under the Boost Software License, Version 1.0.
4// http://www.boost.org/LICENSE_1_0.txt
5
6#if defined(_MSC_VER)
7# pragma warning( disable: 4244 ) // conversion from int to float, possible loss of data
8#endif
9
10#include <boost/variant2/variant.hpp>
11#include <boost/core/lightweight_test.hpp>
12#include <boost/core/lightweight_test_trait.hpp>
13#include <boost/container_hash/hash.hpp>
14#include <boost/config/workaround.hpp>
15#include <vector>
16
17using namespace boost::variant2;
18
19template<template<class...> class Hash, class T1, class T2, class T3> void test()
20{
21 variant<T1, T2, T3> v1( in_place_index_t<0>{} );
22 std::size_t h1 = Hash<decltype(v1)>()( v1 );
23
24 variant<T1, T2, T3> v2( in_place_index_t<1>{} );
25 std::size_t h2 = Hash<decltype(v2)>()( v2 );
26
27 variant<T1, T2, T3> v3( in_place_index_t<2>{} );
28 std::size_t h3 = Hash<decltype(v3)>()( v3 );
29
30 BOOST_TEST_NE( h1, h2 );
31 BOOST_TEST_NE( h1, h3 );
32 BOOST_TEST_NE( h2, h3 );
33}
34
35template<template<class...> class Hash, class T> void test2()
36{
37 variant<T> v1( 0 );
38 std::size_t h1 = Hash<decltype(v1)>()( v1 );
39
40 variant<T> v2( 1 );
41 std::size_t h2 = Hash<decltype(v2)>()( v2 );
42
43 variant<T> v3( 2 );
44 std::size_t h3 = Hash<decltype(v3)>()( v3 );
45
46 BOOST_TEST_NE( h1, h2 );
47 BOOST_TEST_NE( h1, h3 );
48 BOOST_TEST_NE( h2, h3 );
49}
50
51struct X
52{
53 int m = 0;
54};
55
56std::size_t hash_value( X const& x )
57{
58 return boost::hash<int>()( x.m );
59}
60
61struct Y {}; // no hash support
62
63int main()
64{
65 test<std::hash, monostate, monostate, monostate>();
66 test<std::hash, int, int, float>();
67
68 test<boost::hash, monostate, monostate, monostate>();
69 test<boost::hash, int, int, float>();
70
71 test<boost::hash, monostate, X, std::vector<X>>();
72
73 test2<std::hash, int>();
74 test2<std::hash, float>();
75
76 test2<boost::hash, int>();
77 test2<boost::hash, float>();
78
79#if !BOOST_WORKAROUND(BOOST_MSVC, < 1910) && ( !defined(_LIBCPP_STD_VER) || _LIBCPP_STD_VER > 11 )
80
81 BOOST_TEST_TRAIT_FALSE(( detail::is_hash_enabled<Y> ));
82
83#endif
84
85 return boost::report_errors();
86}
87

source code of boost/libs/variant2/test/variant_hash.cpp