Skip to content

Instantly share code, notes, and snippets.

@matovitch
Created October 15, 2018 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matovitch/f01631e29070ed1284409223be073653 to your computer and use it in GitHub Desktop.
Save matovitch/f01631e29070ed1284409223be073653 to your computer and use it in GitHub Desktop.
// https://coliru.stacked-crooked.com/a/0ba6c5762255a8e3
#include <iostream>
#include <utility>
#include <cstdint>
class XorShifter
{
public:
XorShifter(uint64_t seed)
{
_state[0] = seed;
}
uint64_t operator()()
{
uint64_t& s0 = _state[0];
uint64_t& s1 = _state[1];
s0 ^= s0 >> 17;
s0 ^= s0 << 23;
s0 ^= s0 >> 29;
_state[1] += 0x61C8864680B583EB;
return s0 + s1;
}
private:
uint64_t _state[2];
};
template <class Type>
union Hashable
{
public:
template<class... Args>
Hashable(Args&&... args) :
hash{_xorShifter()}
{
new (static_cast<void*>(&_value)) Type(std::forward<Args>(args)...);
}
Type& value() & { return _value ; }
Type&& value() && { return std::move(_value) ; }
const Type& value() const & { return _value ; }
const uint64_t hash;
private:
Type _value;
static XorShifter _xorShifter;
};
template <class Type>
XorShifter Hashable<Type>::_xorShifter{typeid(Type).hash_code()};
int main()
{
Hashable<int> hashableInt = 42;
std::cout << hashableInt.hash << " " << hashableInt.value() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment