-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvariantlist.cpp
133 lines (115 loc) · 1.93 KB
/
variantlist.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*********************************************************
File Name: variantlist.cpp
Author: Abby Cin
Mail: [email protected]
Created Time: Sat 17 Jun 2017 09:18:19 AM CST
**********************************************************/
#include "variant.h"
#include <iostream>
namespace nm
{
template<typename T, typename... Rest>
class variant_list {
private:
struct Node {
variant<T, Rest...> data;
Node *next;
template<typename U>
Node(U &&u, Node *nxt) : data(std::forward<U>(u)), next(nxt)
{
}
};
public:
class iterator {
public:
iterator(Node *n) : data_(n)
{
}
iterator(const iterator &rhs)
{
data_ = rhs.data_;
}
iterator &operator=(const iterator &rhs)
{
if (this != &rhs) {
data_ = rhs.data_;
}
return *this;
}
iterator &operator++()
{
data_ = data_->next;
return *this;
}
bool operator==(const iterator &rhs)
{
return data_ == rhs.data_;
}
bool operator!=(const iterator &rhs)
{
return !(*this == rhs);
}
variant<T, Rest...> *operator->()
{
return &data_->data;
}
variant<T, Rest...> &operator*()
{
return data_->data;
}
private:
Node *data_;
};
public:
variant_list() : root_(nullptr)
{
}
~variant_list()
{
this->clear();
}
template<typename U>
void push(U &&u)
{
if (root_ == nullptr) {
root_ = new Node(std::forward<U>(u), nullptr);
tail_ = root_;
} else {
auto tmp = new Node(std::forward<U>(u), nullptr);
tail_->next = tmp;
tail_ = tmp;
}
}
iterator begin()
{
return iterator(root_);
}
iterator end()
{
return iterator(nullptr);
}
void clear()
{
Node *tmp = nullptr;
while (root_) {
tmp = root_->next;
delete root_;
root_ = tmp;
}
root_ = tail_ = nullptr;
}
private:
Node *root_;
Node *tail_;
};
}
int main()
{
nm::variant_list<int, double, std::string> l;
l.push(233);
l.push(3809.929);
l.push("ha??");
for (auto &x : l) {
std::cout << x << '\n';
}
}