/
any.h
71 lines (58 loc) · 1.31 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 IV_ANY_H_
#define IV_ANY_H_
#include <algorithm>
namespace iv {
namespace core {
class Any {
public:
Any() : ptr_(NULL) { }
// This is Wrapper Class,
// so we cannot set constructor as explicit.
template<typename T>
Any(const T & val) : ptr_(new Holder<T>(val)) { } // NOLINT
template<typename T>
Any(T* val) : ptr_(new Holder<T*>(val)) { } // NOLINT
Any(const Any & other)
: ptr_(other.ptr_ ? other.ptr_->Clone() : NULL) { }
~Any() {
delete ptr_;
}
template<typename T>
T* As() {
return &(static_cast<Holder<T> *>(ptr_)->val_);
}
void Swap(Any& rhs) throw() {
using std::swap;
swap(ptr_, rhs.ptr_);
}
friend void swap(Any& rhs, Any& lhs) {
return rhs.Swap(lhs);
}
template<typename T>
Any& operator=(const T & rhs) {
Any(rhs).Swap(*this); // NOLINT
return *this;
}
Any& operator=(Any & rhs) {
rhs.Swap(*this);
return *this;
}
private:
class Placeholder {
public:
virtual ~Placeholder() { }
virtual Placeholder* Clone() const = 0;
};
template<typename T>
class Holder : public Placeholder {
public:
explicit Holder(const T& val) : val_(val) { }
Placeholder* Clone() const {
return new Holder<T>(val_);
}
T val_;
};
Placeholder* ptr_;
};
} } // namespace iv::core
#endif // IV_ANY_H_