Tuesday, August 30, 2016

Exercise: Use BOOST_STATIC_ASSERT to add error checking to the binary template presented in section 1.4.1 so that binary<N>::value causes a compilation error if N contains digits other than 0 or 1.

#include <iostream>
#include <boost/static_assert.hpp>
template <unsigned long N>
struct binary
{
BOOST_STATIC_ASSERT(N % 10 < 2);
static unsigned const value
= binary<N/10>::value << 1 // prepend higher bits
| N%10; // to lowest bit
};
template <> // specialization
struct binary<0> // terminates recursion
{
static unsigned const value = 0;
};
unsigned const one = binary<1>::value;
unsigned const three = binary<11>::value;
unsigned const two = binary<10>::value;
unsigned const five = binary<101>::value;
unsigned const seven = binary<151>::value;
unsigned const nine = binary<1001>::value;
int main()
{
std::cout << two << std::endl;
return 0;
}

No comments:

Post a Comment