-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrtp_container.cpp
61 lines (56 loc) · 1.4 KB
/
crtp_container.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
// crtp_container.cpp : interface class with derived class using CRTP
// note: compile with -std=c++20 or later
#include <forward_list>
#include <iterator>
#include <initializer_list>
#include <iostream>
using namespace std;
template<typename Derived>
class Container {
Derived& actual() {
return *static_cast<Derived*>(this);
}
const Derived& actual() const {
return *static_cast<const Derived*>(this);
}
public:
decltype(auto) front() {
return *actual().begin();
}
decltype(auto) size() {
return distance(actual().begin(), actual().end());
}
decltype(auto) operator[](size_t i) {
return *next(actual().begin(), i);
}
void print(ostream& os = cout) {
os << "{ ";
for (auto sep = ""; const auto& elem : actual()) {
os << sep << elem;
sep = ", ";
}
os << " }\n";
}
};
template<typename T>
class indexed_list : public Container<indexed_list<T>> {
forward_list<T> l;
public:
indexed_list(const initializer_list<T>& init_list) {
l.assign(init_list);
}
decltype(auto) begin() {
return l.begin();
}
decltype(auto) end() {
return l.end();
}
};
int main() {
indexed_list il{ 1, 2, 3, 4, 5 };
cout << "front(): " << il.front()
<< "\nsize(): " << il.size()
<< "\n[3]: " << il[3] << '\n';
il[4] = 99;
il.print();
}