Meta programming

One of the first meta programming tricks I read about was a structure that calculated how many bits a integer type contained. I needed this calculation for an assignment at a university, where we needed a memory optimized bit vector. The teacher was warning us that he would use different architectures, where the number of bits in various integers types was’t always the same.

We found something like this and a new world of wonders opened up. The magic world of template meta programming.
[cc lang=”c++”]
#include

namespace meta_programming {
#ifdef _WIN32
template struct bitcount {

template struct _bitcount {
static constexpr size_t count = _bitcount<(i << 1)>::count + 1;
};

template<> struct _bitcount<0> {
static constexpr size_t count = 0 ;
};

static constexpr size_t count = _bitcount::count;
};
#else
template struct bitcount {

template struct _bitcount {
static constexpr size_t count = _bitcount<(i << 1), DU>::count + 1;
};

template struct _bitcount<0, DU> {
static constexpr size_t count = 0;
};

static constexpr size_t count = _bitcount::count;
};
#endif
}

int main(int argc, char* argv[]) {

std::cout << meta_programming::bitcount::count << std::endl; std::cout << meta_programming::bitcount::count << std::endl; std::cout << meta_programming::bitcount::count << std::endl; std::cout << meta_programming::bitcount::count << std::endl; std::cout << meta_programming::bitcount::count << std::endl; return 0; } >>> console
bit size of int: 32
bit size of unsigned: 32
bit size of long long: 64
bit size of short: 16
bit size of char: 8

[/cc]

Notes

GCC compiler tested on Coliru.

  • The code don’t compile on all compilers
    • VS 2017 compiles (had to add the #ifdef guard)
    • GCC 4.7 and 5.2 compiles with warnings
    • GCC 7.1 fails with “left operand of shift expression ‘[exp]’ is negative  [-fpermissive]
      • It compiles when only using the unsigned case
    • clang 3.8 fails “error: non-type template argument is not a constant expression  static constexpr size_t count = _bitcount<(i << 1), DU>::count + 1;
  • The “static constexpr size_t count = …;” could be replaced  “enum {count = …};
  • Need support for C++11 (“constexpr” and “long long”)

Leave a Reply

Your email address will not be published. Required fields are marked *