Binary integral literals with template metaprogramming

Sometimes people need to express some integral compile time constants/literals in a binary base form (such as a imaginary “static const int a = 1011b;”). This of course is not supported in C or C++ current standards but it can be easily implemented using C++ template metaprogramming techniques, eventually being able to do something like “static const int a = binary<1011>::value;”.

Limitations:

  • obviously it can only work with representations that are also valid integral literals (“1011” above is actually an integral decimal literal that is converted at compile time to a value as if it were a binary representation)

Improvements: with small modification to the class you could require users of the template to use octal literals so then you could represent more binary values than with integral literals.

Source code is based on various sources I have read in time and fairly small to not claim any copyright over it.

By dizzy with contributions by Edd Dawson.

Recipe source code

#include <boost/static_assert.hpp>

template<unsigned long bin>
struct binary
{
    // Check the literal given for bin contains only 0s and 1s
    BOOST_STATIC_ASSERT(bin % 10 < 2);

    enum { value = 2 * binary<bin/10>::value + bin%2 };
};

template<>
struct binary<0>
{
    enum { value = 0 };
};

Discussion for this page


This is not an official Boost site. For more information on Boost please see Boost.org.