-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathany.cpp
More file actions
88 lines (86 loc) · 1.67 KB
/
Copy pathany.cpp
File metadata and controls
88 lines (86 loc) · 1.67 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include<typeinfo>
#include<string>
using std::cout;
class value_holder {
public:
virtual const std::type_info & type() const= 0;
virtual value_holder * copy() const= 0;
virtual ~value_holder(){}
};
template<typename T>
class holder : public value_holder {
public:
holder(const T &a):data(a){}
T data;
virtual const std::type_info & type() const{
return typeid(T);
}
virtual value_holder *copy() const{
return new holder(data);
}
};
class any {
public:
template<typename T>
any(const T &a):value(new holder<T>(a)){}
any &operator=(any const &a) {
delete value;
value = a.value->copy();
return *this;
}
const std::type_info & type() {
return value ? value->type() : typeid(void);
}
value_holder * value;
any reset() {
delete value;
value = nullptr;
return *this;
}
any swap(any &obj) {
std::swap(value, obj.value);
return *this;
}
bool has_value() {
return value != nullptr;
}
};
template<typename T>
any make_any(T &value) {
return any(value);
}
class bad_any_cast :public std::bad_cast{
public:
virtual const char *what() {
return "bad cast happened!";
}
};
template<typename T>
T any_cast(any &a) {
if (a.type() != typeid(T))
throw bad_any_cast();
return dynamic_cast<holder<T>*>(a.value)->data;
}
int main()
{
any a = 1;
cout << a.type().name() << "\n";
a = 3.14;
cout << a.type().name() << "\n";
if (a.has_value())
cout << "has value!\n";
a.reset();
if (!a.has_value())
cout << "no value!\n";
a = 2.5;
try
{
double b = any_cast<double>(a);
cout << b << "\n";
}
catch (bad_any_cast &e)
{
cout << e.what() << "\n";
}
}