-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtype_erasure.cpp
95 lines (73 loc) · 1.92 KB
/
type_erasure.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
#include <iostream>
#include <variant>
class Animal
{
public:
virtual const char* see() const = 0;
virtual const char* say() const = 0;
};
class Cow : public Animal
{
public:
virtual const char* see() const override { return "cow"; }
virtual const char* say() const override { return "moo"; }
};
class Pig : public Animal
{
public:
virtual const char* see() const override { return "pig"; }
virtual const char* say() const override { return "oink"; }
};
class Dog : public Animal
{
public:
virtual const char* see() const override final { return "dog"; }
virtual const char* say() const override final { return "woof"; }
};
//void seeAndSay(const Animal* const animal_p)
//{
// std::cout << "The animal " << animal_p->see() << " says " << animal_p->say() << "\n";
//}
class Starfish
{
public:
virtual const char* see() const final { return "starfish"; }
virtual const char* say() const final { return "bloop"; }
};
template <typename T>
void seeAndSay(const T* const animal_p)
{
std::cout << "The animal " << animal_p->see() << " says " << animal_p->say() << "\n";
}
class MyAnimal
{
public:
virtual const char* see() const = 0;
virtual const char* say() const = 0;
};
template <typename T>
class AnimalWrapper : public MyAnimal
{
public:
AnimalWrapper(const T& animal) : animal_m(animal) {}
virtual const char* see() const override { return animal_m.see(); }
virtual const char* say() const override { return animal_m.say(); }
private:
const T& animal_m;
};
int main(int argc, char* argv[])
{
MyAnimal* animalArray[] = { new AnimalWrapper(Dog()), new AnimalWrapper(Cow()), new AnimalWrapper(Starfish()) };
for (auto& animal : animalArray)
{
animal->say();
}
seeAndSay(animalArray[0]);
Animal* animalHolder_p = new Dog;
Animal& animalRef = *animalHolder_p;
const char* myDog = animalHolder_p->see();
const char* dogSound = animalRef.say();
// Animal* animalHolder_p = new Dog;
// seeAndSay(animalHolder_p);
return 0;
}