バイナリビットマスク定数テンプレート
cppllの件でちょいと思いついたのでやってみた。
こんなことができる:
std::cout << std::hex << bits<001>::value << "\n" << bits<010>::value << "\n" << bits<011>::value << "\n" << bits<100>::value << "\n" << bits<101>::value << "\n" << bits<110>::value << "\n" << bits<111>::value << "\n" << bits<0111>::value << "\n" << bits<11110111>::value << "\n" << bits<011110111>::value << "\n" << bits<1011110111>::value << std::endl;
結果:
1 2 3 4 5 6 7 7 f7 f7 2f7
実装:
template <int radix, int x, bool check> struct nest2 { const static bool value = false; }; template <int radix, int x, bool cont> struct nest1 { const static bool value = (x > 2) ? false : true; }; template <int radix, int x> struct nest2<radix, x, true> { const static bool value = nest1<radix, x / radix, (x / radix >= radix)>::value; }; template <int radix, int x> struct nest1<radix, x, true> { const static bool value = nest2<radix, x, (x % radix < 2)>::value; }; template <int radix, int x> struct is_ { const static bool value = nest1<radix, x, (x >= radix)>::value; }; template <typename T, int radix, char odd, unsigned int binary> struct to_binary { static const T value = to_binary<T, radix, binary % radix, binary / radix>::value << 1 | odd; }; template <typename T, int radix, char odd> struct to_binary<T, radix, odd, 0> { static const T value = odd; }; template <typename T, bool cond, T t_val, T f_val> struct if_ { const static T value = t_val; }; template <typename T, T t_val, T f_val> struct if_<T, false, t_val, f_val> { const static T value = f_val; }; template <unsigned int binary, typename T = unsigned int> struct bits { static const T value = if_< T, is_<10, binary>::value, to_binary<T, 10, binary % 10, binary / 10>::value, to_binary<T, 8, binary % 8, binary / 8>::value>::value; };