Skip to content

Instantly share code, notes, and snippets.

@tan-wei
Forked from qrealka/bitmasks.cpp
Created April 14, 2024 15:33
Show Gist options
  • Save tan-wei/71030451213ad6234a6f12408fd89c26 to your computer and use it in GitHub Desktop.
Save tan-wei/71030451213ad6234a6f12408fd89c26 to your computer and use it in GitHub Desktop.
c++ compile-time bitmasks
// 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