-
-
Save tan-wei/71030451213ad6234a6f12408fd89c26 to your computer and use it in GitHub Desktop.
c++ compile-time bitmasks
This file contains hidden or 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
// https://stackoverflow.com/questions/54786278/how-do-i-write-a-maintainable-fast-compile-time-bit-mask-in-c | |
#include <bitset> | |
enum Flags { A = 1, B = 2, C = 3, D = 5, | |
E = 8, F = 13, G = 21, H, | |
I, J, K, L, M, N, O }; | |
#define CPP_VERSION 14 | |
#if CPP_VERSION==11 | |
constexpr unsigned long long mask(){ | |
return 0; | |
} | |
template<class...Tail> | |
constexpr unsigned long long mask(unsigned char b0, Tail...tail){ | |
return (1ull<<b0) | mask(tail...); | |
} | |
template< unsigned char... indexes > | |
constexpr unsigned long long mask(){ | |
return mask(indexes...); | |
} | |
#endif | |
#if CPP_VERSION==14 | |
template< unsigned char... indexes > | |
constexpr unsigned long long mask(){ | |
auto r = 0ull; | |
using discard_t = int[]; // data never used | |
// value never used: | |
discard_t discard = {0,(void( | |
r |= (1ull << indexes) // side effect, used | |
),0)...}; | |
(void)discard; // block unused var warnings | |
return r; | |
} | |
#endif | |
#if CPP_VERSION==17 | |
template< unsigned char... indexes > | |
constexpr unsigned long long mask(){ | |
return ((1ull<<indexes)|...|0ull); | |
} | |
#endif | |
void apply_known_mask(std::bitset<64> &bits) { | |
constexpr auto m = mask<B,D,E,H,K,M,L,O>(); | |
bits &= m; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment