C++ Template Metaprogramming
Solutions to the exercises throughout the book
Loading...
Searching...
No Matches
exercise-2-0.hpp
Go to the documentation of this file.
1// ===-- chapter-2/exercise-2-0.hpp ----------------------- -*- C++ -*- --=== //
9#ifndef EXERCISE_2_0
10#define EXERCISE_2_0
11
12#include <boost/type_traits/add_const.hpp>
13#include <boost/type_traits/add_reference.hpp>
14
15
31namespace exercise_2_0 {
32
42namespace no_boost {
43
57template <typename T, bool IsRef>
59{
60 typedef T const& type;
61};
63template <typename T>
64struct add_const_ref_impl<T, true>
65{
66 typedef T type;
67};
68
73template <typename T>
74struct add_const_ref : add_const_ref_impl<T, false> { };
75
77template <typename T>
79
82template <typename T>
83struct add_const_ref<T const> : add_const_ref_impl<T, false> { };
84
85} // namespace no_boost
86
87
95namespace with_boost {
96
101template <typename T>
103{
104 // For int&, add_const has no effect, then add_reference does nothing as
105 // it's already a reference type.
106 typedef typename boost::add_reference<
107 typename boost::add_const<T>::type
109};
110
111} // with_boost
112
119template<typename T>
121
122} // namespace exercise_2_0
123
124#endif // EXERCISE_2_0
Encapsulate solution for Exercise 2-0.
A unary metafunction that returns T if it is a reference type, and otherwise returns T const&.
The default implementation adds a const& to the template type.
This is a home-grown implementation to the problem.
boost::add_reference< typenameboost::add_const< T >::type >::type type