C++ Template Metaprogramming
Solutions to the exercises throughout the book
Loading...
Searching...
No Matches
exercise-2-2.hpp
Go to the documentation of this file.
1// ===-- chapter-2/exercise-2-2.hpp ----------------------- -*- C++ -*- --=== //
9#ifndef EXERCISE_2_2
10#define EXERCISE_2_2
11
12#include <boost/static_assert.hpp>
13#include <boost/type_traits/add_pointer.hpp>
14#include <boost/type_traits/is_reference.hpp>
15#include <boost/type_traits/remove_reference.hpp>
16
17#include <assert.h>
18
19
39namespace exercise_2_2 {
40
54template <typename Target, typename Source>
55inline Target polymorphic_downcast(Source *const x)
56{
57 assert(dynamic_cast<Target>(x) == x);
58 return static_cast<Target>(x);
59}
60
74template <typename Target, typename Source>
75inline Target polymorphic_downcast(Source& x)
76{
77 BOOST_STATIC_ASSERT((boost::is_reference<Target>::value));
78
79 // NOTE: If a Source defines operator&, this can lead to undesired results.
80 assert(
81 dynamic_cast<
82 typename boost::add_pointer<
83 typename boost::remove_reference<Target>::type
84 >::type>(&x)
85 == &x);
86 return static_cast<Target>(x);
87}
88
89} // namespace exercise_2_2
90
91#endif // EXERCISE_2_2
BOOST_STATIC_ASSERT((boost::is_same< t5, expected_t5 >::value))
Target polymorphic_downcast(Source *const x)
Check the validity of a downcast.
Encapsulate solution for Exercise 2-2.