[Home]CPPTM Answers - Exercise 3-0

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

 // (by Ariel Badichi)
 #include <iostream>

 #include <boost/static_assert.hpp>

 template<unsigned int N>
 struct binary
 {
     static const unsigned int digit = N % 10;
     BOOST_STATIC_ASSERT(digit == 0 || digit == 1);
     static const unsigned int value = digit + (binary<N / 10>::value * 2);
 };

 template<>
 struct binary<0>
 {
     static const unsigned int value = 0;
 };

 int main()
 {
     // add a 2 and see what happens ;)
     std::cout << binary<101010>::value << "\n";
     return 0;
 }


my answer, similar but different (note: this editor is messing with my text so look at this in the editor as it does not appear that way on the site)...

  1. include <boost/static_assert.hpp>
  2. include <boost/mpl/int.hpp>

  1. ifdef NDEBUG
  2. define CTASSERT(x)
  3. else
  4. define CTASSERT(x) BOOST_STATIC_ASSERT(x)
  5. endif

template<unsigned long N> class binary: public boost::mpl::int_<boost::mpl::int_<binary<N/10>::value>::value<<1 | N%10> {

	CTASSERT((N%10 & ~1) == 0);
};

template<> class binary<0>: public boost::mpl::int_<0> { };


BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited January 27, 2008 10:03 pm (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers