C++ Template Metaprogramming
Solutions to the exercises throughout the book
Loading...
Searching...
No Matches
c++20/chapter-1.cpp
Go to the documentation of this file.
1// ===-- chapter-1/c++20/chapter-1.cpp -------------------- -*- C++ -*- --=== //
9#include <cstdint>
10#include <stdio.h>
11
12
13namespace chapter1 {
14
17inline namespace cpp20 {
18
26constexpr uint32_t binary_func(uint64_t const N)
27{
28 return (N == 0) ? 0 : (N % 10) + (2 * binary_func(N/10));
29}
30
38consteval uint32_t binary(uint64_t const N)
39{
40 return binary_func(N);
41}
42
43} // inline namespace cpp20
44} // namespace chapter1
45
46
47namespace {
48using namespace chapter1;
49
58constexpr struct { uint32_t expected; uint32_t got; } run[] = {
59 {.expected = 1, .got = binary(1)},
60 {.expected = 3, .got = binary(11)},
61 {.expected = 5, .got = binary(101)},
62 {.expected = 7, .got = binary(111)},
63 {.expected = 9, .got = binary(1001)},
64};
65
66} // namespace <anon>
67
68int main()
69{
70 using namespace chapter1;
71
72 for (auto const& vals : run) {
73 printf("Should be %u: %u\n", vals.expected, vals.got);
74 }
75 return 0;
76}
int main()
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.
Prepend higher bits to lowest bit.
Definition: chapter-1.cpp:47