forked from hsf-training/cpluspluscourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvariant.cpp
40 lines (31 loc) · 803 Bytes
/
variant.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
/*
In the code below, replace inheritance with the use of a std::variant.
Two solutions are provided :
1. with `std::get_if`,
2. with `std::visit`.
*/
#include <iostream>
#include <memory>
#include <vector>
struct Particle {
virtual void print() const = 0;
virtual ~Particle() = default;
};
struct Electron : Particle {
void print() const override { std::cout << "E\n"; }
};
struct Proton : Particle {
void print() const override { std::cout << "P\n"; }
};
struct Neutron : Particle {
void print() const override { std::cout << "N\n"; }
};
int main() {
std::vector<std::unique_ptr<Particle>> ps;
ps.push_back(std::make_unique<Electron>());
ps.push_back(std::make_unique<Proton>());
ps.push_back(std::make_unique<Neutron>());
for (auto const &p : ps) {
p->print();
}
}