-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAny.h
71 lines (63 loc) · 1.64 KB
/
Any.h
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
#ifndef __ANY_H__
#define __ANY_H__
#include <typeindex>
#include <memory>
using namespace std;
namespace template_learning {
class any {
public:
any(void):m_tpIdx(std::type_index(typeid(void))) {}
any(any& that) : m_ptr(that.clone()), m_tpIdx(that.m_tpIdx) {}
any(any&& that) : m_ptr(std::move(that.m_ptr)), m_tpIdx(that.m_tpIdx) {}
template<class U,
class = typename std::enable_if<!is_same<typename std::decay<U>::type, any>::value,U>::type>
any(U&& value) : m_ptr(new derived<typename decay<U>::type>(forward<U>(value))), m_tpIdx(type_index(typeid(typename decay<U>::type))) {}
// template<class U >
// U& AnyCast()
// {
// if (!Is<U>())
// {
// throw std::bad_cast();
// }
// auto dd = dynamic_cast<derived<U>*> (m_ptr.get());
// return dd->m_value;
// }
template<class U >
U& fCast()
{
// warning :
// @todo : reinterpret_cast<> == static_cast<> ;
auto dd = reinterpret_cast< derived<U>* >(m_ptr.get());
return dd->m_value;
}
private:
class base;
using basePtr = std::unique_ptr<base>;
class base {
public:
virtual ~base() {}
virtual basePtr clone() const=0;
};
template<class T>
class derived : public base
{
public:
template<class U>
derived(U && value) : m_value(forward<U>(value)) {}
basePtr clone() const {
return basePtr(new derived<T>(m_value));
}
T m_value;
};
basePtr clone() const
{
if (m_ptr != nullptr)
return m_ptr->clone();
return nullptr;
}
private:
std::type_index m_tpIdx;
basePtr m_ptr;
};
}
#endif // __ANY_H__