Last active
August 29, 2015 14:26
-
-
Save seanmiddleditch/8ac7a528faa3cd8225e4 to your computer and use it in GitHub Desktop.
Strong enum handle example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename HandleT, unsigned IndexBits = 24U> | |
HandleT pack(unsigned index, unsigned version) { | |
using T = std::underline_type<HandleT>::type; | |
auto result = T(version << IndexBits); | |
auto const mask = T(1 << IndexBits) - 1; | |
result |= T(index) & mask; | |
return HandleT(result); | |
} | |
template <typename HandleT> | |
void unpack(HandleT handle, unsigned& out_index, unsigned& out_version) { | |
using T = std::underline_type<HandleT>::type; | |
auto const mask = T(1 << IndexBits) - 1; | |
out_index = T(handle) & mask; | |
out_version = T(handle) >> IndexBits; | |
} | |
// --- example --- | |
enum class TextureId : std::uint32_t { None = 0 }; | |
// make a new texture ID | |
TextureId tex = pack<TextureId>(my_index, my_version); | |
// extract the index and version from a texture ID | |
unsigned index, version; | |
unpack(tex, index, version); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment