The problem is simple: tell if a number contains consecutive 1's.
It is not simple if we want to know the value in compile time:
/////////
//template <unsigned M, unsigned S> struct Status<2, 1, M, S> { const static bool b = false;};
//If I use this line, the default template (the 1st one) can be just a declaration.
/////////
//I indicates the status #, N is the rightmost bit, M is the current code, S is the remaining bits to handle
#include <iostream>
template <unsigned I, unsigned N, unsigned M, unsigned S> struct Status{ const static bool is = false;};
template <unsigned M> struct Status<1, 1, M, 0> { const static bool is = true;};
template <unsigned M> struct Status<2, 0, M, 0> { const static bool is = true;};
template <unsigned M, unsigned S> struct Status<2, 0, M, S> { const static bool is = Status<2, M%2, (M>>1), S-1>::is;};
template <unsigned M, unsigned S> struct Status<1, 1, M, S> { const static bool is = Status<1, M%2, (M>>1), S-1>::is;};
template <unsigned M, unsigned S> struct Status<1, 0, M, S> { const static bool is = Status<2, M%2, (M>>1), S-1>::is;};
template <unsigned M, unsigned S> struct Status<0, 0, M, S> { const static bool is = Status<0, M%2, (M>>1), S-1>::is;};
template <unsigned M, unsigned S> struct Status<0, 1, M, S> { const static bool is = Status<1, M%2, (M>>1), S-1>::is;};
template <unsigned CODE> struct IsConsec {const static bool is = Status<0, CODE%2, CODE, sizeof(unsigned)*8 >::is;};
int main()
{
const unsigned code0 = 0xffffff0f, code1 = 0x3fffffff;
using namespace std;
cout<<boolalpha;
cout<<IsConsec<code0>::is<<endl;
cout<<IsConsec<code1>::is<<endl;
}
No comments:
Post a Comment