-
Notifications
You must be signed in to change notification settings - Fork 79
/
8.4variant存储不同的类型.cpp
68 lines (61 loc) · 1.71 KB
/
8.4variant存储不同的类型.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
#include"print.h"
#include<string_view>
#include<variant>
#include<list>
class Animal {
std::string_view _name{};
std::string_view _sound{};
public:
Animal(std::string_view n, std::string_view s) :_name{ n }, _sound{ s } {}
void speak()const {
print("{} says {}\n", _name, _sound);
}
void sound(std::string_view s) {
_sound = s;
}
};
class Cat :public Animal {
public:
Cat(std::string_view n):Animal(n,"meow"){}
};
class Dog :public Animal {
public:
Dog(std::string_view n) :Animal(n, "arf!"){}
};
class Wookie :public Animal {
public:
Wookie(std::string_view n) :Animal(n, "grrraarrgghh!"){}
};
struct animal_speaks {
void operator()(const Dog& d)const { d.speak(); }
void operator()(const Cat& c)const { c.speak(); }
void operator()(const Wookie& w)const { w.speak(); }
};
using v_animal = std::variant<Cat, Dog, Wookie>;
int main() {
std::list<v_animal>pets{ Cat{"Hobbes"},Dog{"Fido"},Cat{"Max"},Wookie{"Chewie"} };
for (const v_animal& a : pets) {
std::visit(animal_speaks{}, a);
}
for (const v_animal& a : pets) {
auto idx{ a.index() };
if (idx == 0)std::get<Cat>(a).speak();
if (idx == 1)std::get<Dog>(a).speak();
if (idx == 2)std::get<Wookie>(a).speak();
}
for (const v_animal& a : pets) {
if (const auto c{ std::get_if<Cat>(&a) }; c)
c->speak();
else if (const auto d{ std::get_if<Dog>(&a) }; d)
d->speak();
else if (const auto w{ std::get_if<Wookie>(&a) }; w)
w->speak();
}
size_t n_cats{}, n_dogs{}, n_wookies{};
for (const v_animal& a : pets) {
if (std::holds_alternative<Cat>(a))++n_cats;
if (std::holds_alternative<Dog>(a))++n_dogs;
if (std::holds_alternative<Wookie>(a))++n_wookies;
}
print("there are {} cat(s),{} dog(s),and {} wookie(s)\n", n_cats, n_dogs, n_wookies);
}