C++ Template Metaprogramming
Solutions to the exercises throughout the book
All Classes Namespaces Files Functions Variables Typedefs Macros Modules Pages
c++20/exercise-2-2.hpp
Go to the documentation of this file.
1// ===-- chapter-2/c++20/exercise-2-2.hpp ----------------- -*- C++ -*- --=== //
9#ifndef EXERCISE_2_2
10#define EXERCISE_2_2
11
12#include <assert.h>
13#include <memory>
14#include <type_traits>
15
16
17namespace exercise_2_2 {
18
21inline namespace cpp20 {
22
36template <typename Target, typename Source>
37inline Target polymorphic_downcast(Source *const x)
38{
39 assert(dynamic_cast<Target>(x) == x);
40 return static_cast<Target>(x);
41}
42
56template <typename Target, typename Source>
57inline Target polymorphic_downcast(Source& x)
58{
59 static_assert(std::is_reference<Target>::value);
60
61 // NOTE: If a Source defines operator&, this can lead to undesired results.
62 assert(
63 dynamic_cast<
64 typename std::add_pointer<
65 typename std::remove_reference<Target>::type
66 >::type>(std::addressof(x))
67 == std::addressof(x));
68 return static_cast<Target>(x);
69}
70
71} // inline namespace cpp20
72} // namespace exercise_2_2
73
74#endif // EXERCISE_2_2
Target polymorphic_downcast(Source *const x)
Check the validity of a downcast.
Encapsulate solution for Exercise 2-2.