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:
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.
#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 };
};
This is not an official Boost site. For more information on Boost please see Boost.org.