C++ Template Metaprogramming
Solutions to the exercises throughout the book
Loading...
Searching...
No Matches
chapter-1.cpp
Go to the documentation of this file.
1// ===-- chapter-1/chapter-1.cpp -------------------------- -*- C++ -*- --=== //
9#include <stdio.h>
10
11
26namespace chapter1 {
27
35unsigned binary_func(unsigned long const N)
36{
37 return (N == 0) ? 0 : (N % 10) + (2 * binary_func(N/10));
38}
39
45template <unsigned long N>
46struct binary
47{
48 static unsigned const value = (binary<N/10>::value * 2) + (N % 10);
49};
50
52template<>
53struct binary<0>
54{
55 static unsigned const value = 0;
56};
57
58} // namespace chapter1
59
60
61namespace {
62using namespace chapter1;
63
73 unsigned const expected; unsigned const got;
74} const run[] = {
75 {.expected = 1, .got = binary<1>::value},
76 {.expected = 3, .got = binary<11>::value},
77 {.expected = 5, .got = binary<101>::value},
78 {.expected = 7, .got = binary<111>::value},
79 {.expected = 9, .got = binary<1001>::value},
80};
81
82} // namespace <anon>
83
84int main()
85{
86 using namespace chapter1;
87
88 for (size_t i = 0; i < sizeof(run) / sizeof(*run); ++i) {
89 printf("Should be %u: %u\n", run[i].expected, run[i].got);
90 }
91 return 0;
92}
int main()
Definition: chapter-1.cpp:84
constexpr struct anonymous_namespace{chapter-1.cpp}::@0 run[]
the container for test input and output.
constexpr uint32_t binary_func(uint64_t const N)
A runtime binary to decimal number translation.
Solutions for Chapter 1.
the container for test input and output.
Definition: chapter-1.cpp:72
Prepend higher bits to lowest bit.
Definition: chapter-1.cpp:47
static unsigned const value
Definition: chapter-1.cpp:48