forked from parallel101/course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd.cpp
76 lines (59 loc) · 1.76 KB
/
d.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
#include <memory>
#include <string>
#include <iostream>
using namespace std;
struct IObject {
IObject() = default;
IObject(IObject const &) = default;
IObject &operator=(IObject const &) = default;
virtual ~IObject() = default;
virtual void eatFood() = 0;
virtual shared_ptr<IObject> clone() const = 0;
};
template <class Derived, class Base = IObject>
struct IObjectClone : Base {
virtual shared_ptr<IObject> clone() const override {
Derived const *that = static_cast<Derived const *>(this);
return make_shared<Derived>(*that);
}
};
struct CatObject : IObjectClone<CatObject> {
string m_catFood = "someFish";
virtual void eatFood() override {
cout << "eating " << m_catFood << endl;
m_catFood = "fishBones";
}
virtual ~CatObject() override = default;
};
struct DogObject : IObjectClone<DogObject> {
string m_dogFood = "someMeat";
virtual void eatFood() override {
cout << "eating " << m_dogFood << endl;
m_dogFood = "meatBones";
}
virtual ~DogObject() override = default;
};
template <class AnimalTagT>
struct AnimalObject : IObjectClone<AnimalObject<AnimalTagT>> {
AnimalTagT m_someTag;
// ...
};
struct SuperDogObject : IObjectClone<SuperDogObject, DogObject> {
virtual void eatFood() override {
DogObject::eatFood();
cout << "WOOAHHH!!! I'm SUPERDOG~~~!!" << endl;
}
virtual ~SuperDogObject() override = default;
};
void eatTwice(IObject *obj) {
shared_ptr<IObject> newObj = obj->clone();
obj->eatFood();
newObj->eatFood();
}
int main() {
shared_ptr<CatObject> cat = make_shared<CatObject>();
shared_ptr<DogObject> dog = make_shared<DogObject>();
eatTwice(cat.get());
eatTwice(dog.get());
return 0;
}