Skip to content

Instantly share code, notes, and snippets.

@gorlak
Last active December 23, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gorlak/6643972 to your computer and use it in GitHub Desktop.
Save gorlak/6643972 to your computer and use it in GitHub Desktop.
Template meta-program for bit counting of constants
#include <stdint.h>
template< uint32_t x >
struct PopCount
{
static const uint32_t n = PopCount< x / 2 >::n + ( x % 2 );
};
template<>
struct PopCount< 0 >
{
static const uint32_t n = 0;
};
const static uint32_t a = PopCount<2>::n;
const static uint32_t b = PopCount<4>::n;
const static uint32_t c = PopCount<3>::n;
const static uint32_t d = PopCount<5>::n;
static_assert( a == b, "bit count mismatch in compile constant" );
static_assert( c == d, "bit count mismatch in compile constant" );
static_assert( a != c, "bit count mismatch in compile constant" );
static_assert( b != d, "bit count mismatch in compile constant" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment