forked from caiorss/C-Cpp-Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
property-type-erasure1.cpp
64 lines (56 loc) · 1.34 KB
/
property-type-erasure1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Author: Caio Rodrigues
// Brief: Property class without type erasure.
//-----------------------------------------------
#include <iostream>
#include <string>
#include <functional>
#include <iomanip>
/** Class that encapsulate get/set properties
* @tparam - Type default constructible, copiable and equality-comparable
*/
template <typename T>
class TProperty
{
std::string m_name;
T m_value;
std::type_info const& m_tinfo;
public:
TProperty(std::string name, T const& init = T{})
: m_name(std::move(name))
, m_value(init)
, m_tinfo(typeid(T))
{ }
std::string Name() const
{
return m_name;
}
const std::type_info& Type()
{
return m_tinfo;
}
TProperty<T> Get() const
{
return m_value;
}
TProperty<T>& Set(T const& value)
{
std::cerr << " [TRACE] Property [" << m_name << "] set to value = "
<< value << std::endl;
m_value = value;
}
friend std::ostream& operator<<(std::ostream& os, TProperty<T> const& rhs)
{
return os << " Property{ Name = " << std::quoted(rhs.m_name)
<< " ; Value = " << rhs.m_value << " }";
}
};
int main()
{
TProperty<int> p1("count", 100);
TProperty<double> p2("range", 5.6);
TProperty<std::string> p3("name", "Box");
std::cout << "p1 = " << p1 << "\n";
std::cout << "p2 = " << p2 << "\n";
std::cout << "p3 = " << p3 << "\n";
return 0;
}