C++ Library Extensions 2022.12.09
To help learn modern C++ programming
05-unique_ptr.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
6template<typename ElementType>
7class DummyClass
8{
9 public:
10 using uptr_t = std::unique_ptr<ElementType>;
11 using lref_uptr_t = std::unique_ptr<ElementType>&;
12 using const_lref_uptr_t = const std::unique_ptr<ElementType>&;
13 using rref_uptr_t = std::unique_ptr<ElementType>&&;
14
15 private:
16 uptr_t m_member;
17
18 public:
19 DummyClass(ElementType value = ElementType{}):
20 m_member{ std::make_unique<ElementType>(value) } { }
21
22 // we introduced template parameter Type
23 // which breaks the tie between DummyClass ('s template parameter ElementType)
24 // and its member get_member()
25 template<typename Type = const_lref_uptr_t>
27 {
28 return static_cast<Type>(this->m_member);
29 }
30};
31
33{
34 using dummy_t = DummyClass<double>;
35
36 dummy_t dummy{ 22.0 / 7.0 };
37
38
39 // auto is copy semantic.
40 auto& p1 = dummy.get_member();
41
42 stream <<"the value of the object that p1 is pointing to is "
43 << *p1 << endl;
44
45 stream << "The type of p1: "
46 << Tpf_GetTypeCategory(p1) << endl;
47
48 auto& p2 = dummy.get_member<dummy_t::lref_uptr_t>();
49
50 stream <<"the value of the object that p2 is pointing to is "
51 << *p2 << endl;
52
53 stream << "The type of p2: "
54 << Tpf_GetTypeCategory(p2) << endl;
55
56
57 // now, it is "move semantic"
58 auto p3 = dummy.get_member<dummy_t::rref_uptr_t>();
59
60 stream <<"the value of the object that p3 is pointing to is "
61 << *p3 << endl;
62
63 stream << "The type of p3: "
64 << Tpf_GetTypeCategory(p3) << endl;
65}
66
67int main()
68{
70}
tpf::sstream stream
auto endl
int main()
void test_get_member()
Type get_member()
decltype(auto) get_member()
std::unique_ptr< ElementType > && rref_uptr_t
DummyClass(ElementType value=ElementType{})
std::unique_ptr< int > uptr_t
std::unique_ptr< ElementType > & lref_uptr_t
const std::unique_ptr< ElementType > & const_lref_uptr_t
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.
#define Tpf_GetTypeCategory(instance_arg)
A macro that returns instance_arg's type category string name.
Definition: tpf_types.hpp:1428