-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTypeErasure.cpp
More file actions
694 lines (518 loc) · 19.5 KB
/
TypeErasure.cpp
File metadata and controls
694 lines (518 loc) · 19.5 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// =====================================================================================
// TypeErasure.cpp
// =====================================================================================
module;
#include "../ScopedTimer/ScopedTimer.h"
module modern_cpp:type_erasure;
namespace {
std::size_t MaxIterations = 1000000;
//std::size_t MaxIterations = 100000;
}
// =====================================================================================
namespace TypeErasureUsingDynamicPolymorphism {
struct IAnimal
{
virtual ~IAnimal() = default;
virtual std::string see() const = 0;
virtual std::string say() const = 0;
};
class Dog : public IAnimal
{
public:
virtual std::string see() const override { return "dog"; }
virtual std::string say() const override { return "woof"; }
};
class Cat : public IAnimal
{
public:
virtual std::string see() const override { return "cat"; }
virtual std::string say() const override { return "meow"; }
};
using AnimalPointer = std::shared_ptr<IAnimal>;
using Animals = std::vector<AnimalPointer>;
static void test_type_erasure_using_dynamic_polymorphism()
{
AnimalPointer animal1{ std::make_shared<Cat>() };
AnimalPointer animal2{ std::make_shared<Dog>() };
Animals animals{ animal1, animal2 };
for (const auto& animal : animals) {
std::println("{}: {}", animal->see(), animal->say());
}
std::println();
}
}
// =====================================================================================
namespace TypeErasureUsingTemplateTechniques {
class Dog
{
public:
std::string see() const { return "dog"; }
std::string say() const { return "woof"; }
};
class Cat
{
public:
std::string see() const { return "cat"; }
std::string say() const { return "meow"; }
};
class PolymorphicObjectWrapper
{
public:
template<typename T>
PolymorphicObjectWrapper(const T& obj) :
m_wrappedObject{ std::make_shared<ObjectModel<T>>(obj) }
{}
std::string see() const
{
return m_wrappedObject->see();
}
std::string say() const
{
return m_wrappedObject->say();
}
private:
struct ObjectConcept
{
virtual ~ObjectConcept() = default;
virtual std::string see() const = 0;
virtual std::string say() const = 0;
};
template<typename T>
struct ObjectModel final : public ObjectConcept
{
ObjectModel(const T& object) : m_object{ object } {}
std::string see() const override
{
return m_object.see();
}
std::string say() const override
{
return m_object.say();
}
private:
T m_object;
};
std::shared_ptr<ObjectConcept> m_wrappedObject;
};
using Animals = std::vector<PolymorphicObjectWrapper>;
static void test_type_erasure_using_template_techniques()
{
Animals animals{ Cat(), Dog() };
for (const auto& animal : animals) {
std::println("{}: {}", animal.see(), animal.say());
}
std::println();
}
}
// =====================================================================================
namespace TypeErasureUsingTemplateTechniquesAndConcepts {
class Dog
{
public:
std::string see() const { return "dog"; }
std::string say() const { return "woof"; }
};
class Cat
{
public:
std::string see() const { return "cat"; }
std::string say() const { return "meow"; }
};
template<typename T>
concept ClassActingLikeAnAnimal = requires (const T & o)
{
{ o.see() } -> std::same_as<std::string>;
{ o.say() } -> std::same_as<std::string>;
};
class PolymorphicObjectWrapper
{
public:
template<typename T>
requires ClassActingLikeAnAnimal<T>
PolymorphicObjectWrapper(const T& obj) :
m_wrappedObject{ std::make_shared<ObjectModel<T>>(obj) }
{}
std::string see() const
{
return m_wrappedObject->see();
}
std::string say() const
{
return m_wrappedObject->say();
}
private:
struct ObjectConcept
{
virtual ~ObjectConcept() = default;
virtual std::string see() const = 0;
virtual std::string say() const = 0;
};
template<typename T>
requires ClassActingLikeAnAnimal<T>
struct ObjectModel final : public ObjectConcept
{
ObjectModel(const T& object) : m_object{ object } {}
std::string see() const override
{
return m_object.see();
}
std::string say() const override
{
return m_object.say();
}
private:
T m_object;
};
std::shared_ptr<ObjectConcept> m_wrappedObject;
};
using Animals = std::vector<PolymorphicObjectWrapper>;
static void test_type_erasure_using_template_techniques()
{
Animals animals{ Cat(), Dog() };
for (const auto& animal : animals) {
std::println("{}: {}", animal.see(), animal.say());
}
std::println();
}
}
// =====================================================================================
namespace BookStoreUsingDynamicPolymorphism {
struct IMedia
{
virtual ~IMedia() = default;
virtual double getPrice() const = 0;
virtual std::size_t getCount() const = 0;
};
class Book : public IMedia
{
private:
std::string m_author;
std::string m_title;
double m_price;
std::size_t m_count;
public:
// c'tor
Book(const std::string& author, const std::string& title, double price, std::size_t count)
: m_author{ author }, m_title{ title }, m_price{ price }, m_count{ count }
{}
// getter / setter
const std::string& getAuthor() const { return m_author; }
const std::string& getTitle() const { return m_title; }
// interface 'IMedia'
double getPrice() const override { return m_price; }
std::size_t getCount() const override { return m_count; }
};
class Movie : public IMedia
{
private:
std::string m_title;
std::string m_director;
double m_price;
std::size_t m_count;
public:
// c'tor
Movie(const std::string& title, const std::string& director, double price, std::size_t count)
: m_title{ title }, m_director{ director }, m_price{ price }, m_count{ count }
{ }
// getter / setter
const std::string& getTitle() const { return m_title; }
const std::string& getDirector() const { return m_director; }
// interface 'IMedia'
double getPrice() const override { return m_price; }
std::size_t getCount() const override { return m_count; }
};
class Bookstore
{
private:
using Stock = std::vector<std::shared_ptr<IMedia>>;
using StockList = std::initializer_list<std::shared_ptr<IMedia>>;
Stock m_stock;
public:
// c'tor
explicit Bookstore(StockList stock) : m_stock{ stock } {}
// public interface
double totalBalance() const {
double total{};
for (const auto& media : m_stock) {
total += media->getPrice() * media->getCount();
}
return total;
}
std::size_t count() const {
std::size_t total{};
for (const auto& media : m_stock) {
total += media->getCount();
}
return total;
}
void addMedia(const std::shared_ptr<IMedia>& media) {
m_stock.push_back(media);
}
};
static void test_bookstore_polymorphic_01() {
std::shared_ptr<IMedia> cBook{ std::make_shared<Book>("C", "Dennis Ritchie", 11.99, 12) };
std::shared_ptr<IMedia> javaBook{ std::make_shared<Book>("Java", "James Gosling", 17.99, 21) };
std::shared_ptr<IMedia> cppBook{ std::make_shared<Book>("C++", "Bjarne Stroustrup", 16.99, 4) };
std::shared_ptr<IMedia> csharpBook{ std::make_shared<Book>("C#", "Anders Hejlsberg", 21.99, 8) };
std::shared_ptr<IMedia> movieTarantino{ std::make_shared<Movie>("Once upon a time in Hollywood", "Quentin Tarantino", 6.99, 3) };
std::shared_ptr<IMedia> movieBond{ std::make_shared<Movie>("Spectre", "Sam Mendes", 8.99, 6) };
Bookstore bookstore{
cBook, movieBond, javaBook, cppBook, csharpBook, movieTarantino
};
double balance{ bookstore.totalBalance() };
std::println("Total value of Bookstore: {:.{}f}", balance, 2);
std::size_t count{ bookstore.count() };
std::println("Count of elements in Bookstore: {}", count);
}
static void test_bookstore_polymorphic_02() {
std::shared_ptr<IMedia> cBook{ std::make_shared<Book>("C", "Dennis Ritchie", 11.99, 12) };
std::shared_ptr<IMedia> movieBond{ std::make_shared<Movie>("Spectre", "Sam Mendes", 8.99, 6) };
Bookstore bookstore{ cBook, movieBond };
std::shared_ptr<IMedia> csharpBook{ std::make_shared<Book>("C#", "Anders Hejlsberg", 21.99, 8) };
bookstore.addMedia(csharpBook);
std::shared_ptr<IMedia> movieTarantino{ std::make_shared<Movie>("Once upon a time in Hollywood", "Quentin Tarantino", 6.99, 3) };
bookstore.addMedia(movieTarantino);
std::size_t count{ bookstore.count() };
std::println("Count of elements in Bookstore: {}", count);
}
static void test_bookstore_polymorphic_03() {
std::println("Benchmark - Method Call - using Polymorphism");
std::shared_ptr<IMedia> cBook{ std::make_shared<Book>("C", "Dennis Ritchie", 11.99, 12) };
ScopedTimer watch{};
double total{};
for (std::size_t i{}; i != MaxIterations; ++i) {
total += cBook->getCount() * cBook->getPrice();
}
std::print("Done: ");
}
static void test_bookstore_polymorphic_04() {
std::println("Benchmark - Iterating a Container of Shared Pointers - using Polymorphism");
Bookstore bookstore{ };
std::shared_ptr<IMedia> cBook{ std::make_shared<Book>("C", "Dennis Ritchie", 11.99, 12) };
for (std::size_t i{}; i != 100; ++i) {
bookstore.addMedia(cBook);
}
ScopedTimer watch{};
double total{};
for (std::size_t i{}; i != MaxIterations; ++i) {
double totalBalance{ bookstore.totalBalance() };
total += totalBalance;
}
std::print("Done: ");
}
}
// =====================================================================================
namespace BookStoreUsingTypeErasure {
class Book
{
private:
std::string m_author;
std::string m_title;
double m_price;
std::size_t m_count;
public:
// c'tor
Book(const std::string& author, const std::string& title, double price, std::size_t count)
: m_author{ author }, m_title{ title }, m_price{ price }, m_count{ count }
{}
// getter / setter
const std::string& getAuthor() const { return m_author; }
const std::string& getTitle() const { return m_title; }
double getPrice() const { return m_price; }
std::size_t getCount() const { return m_count; }
};
class Movie
{
private:
std::string m_title;
std::string m_director;
double m_price;
std::size_t m_count;
public:
// c'tor
Movie(const std::string& title, const std::string& director, double price, std::size_t count)
: m_title{ title }, m_director{ director }, m_price{ price }, m_count{ count }
{ }
// getter / setter
const std::string& getTitle() const { return m_title; }
const std::string& getDirector() const { return m_director; }
double getPrice() const { return m_price; }
std::size_t getCount() const { return m_count; }
};
template<typename T>
concept MediaConcept = requires (const T & m)
{
{ m.getPrice() } -> std::same_as<double>;
{ m.getCount() } -> std::same_as<std::size_t>;
};
template <typename ... TMedia>
requires (MediaConcept<TMedia> && ...)
class Bookstore
{
private:
using StockType = std::variant<TMedia ...>;
using Stock = std::vector<StockType>;
using StockList = std::initializer_list<StockType>;
Stock m_stock;
public:
explicit Bookstore(StockList stock) : m_stock{ stock } {}
// template member method
template <typename T>
requires MediaConcept<T>
void addMedia(const T& media) {
m_stock.push_back(StockType{ media }); // detailed notation
// m_stock.push_back(media); // implicit type conversion (T => std::variant<T>)
}
// or
void addMediaEx(const MediaConcept auto& media) {
m_stock.push_back(media);
}
// public interface
double totalBalance() const {
double total{};
for (const auto& media : m_stock) {
double price{};
std::size_t count{};
std::visit(
[&](const auto& element) {
price = element.getPrice();
count = element.getCount();
},
media
);
total += price * count;
}
return total;
}
std::size_t count() const {
std::size_t total{};
for (const auto& media : m_stock) {
std::size_t count{};
std::visit(
[&](const auto& element) {
count = element.getCount();
},
media
);
total += count;
}
return total;
}
// -----------------------------------------------
// demonstrating std::visit with returning a value
double totalBalanceEx() const {
double total{};
for (const auto& media : m_stock) {
total += std::visit(
[](const auto& element) {
double price = element.getPrice();
std::size_t count = element.getCount();
return price * count;
},
media
);
}
return total;
}
std::size_t countEx() const {
std::size_t total{};
for (const auto& element : m_stock) {
total += std::visit(
[](const auto& element) {
return element.getCount();
},
element
);
}
return total;
}
};
static void test_bookstore_type_erasure_01() {
Book cBook{ "C", "Dennis Ritchie", 11.99, 12 };
Book javaBook{ "Java", "James Gosling", 17.99, 21 };
Book cppBook{ "C++", "Bjarne Stroustrup", 16.99, 4 };
Book csharpBook{ "C#", "Anders Hejlsberg", 21.99, 8 };
Movie movieTarantino{ "Once upon a time in Hollywood", "Quentin Tarantino", 6.99, 3 };
Movie movieBond{ "Spectre", "Sam Mendes", 8.99, 6 };
using MyBookstore = Bookstore<Book, Movie>;
MyBookstore bookstore{
cBook, movieBond, javaBook, cppBook, csharpBook, movieTarantino
};
double balance{ bookstore.totalBalance() };
std::println("Total value of Bookstore: {:.{}f}", balance, 2);
std::size_t count{ bookstore.count() };
std::println("Count of elements in Bookstore: {}", count);
}
static void test_bookstore_type_erasure_02() {
Book cBook{ "C", "Dennis Ritchie", 11.99, 12 };
Movie movieBond{ "Spectre", "Sam Mendes", 8.99, 6 };
using MyBookstore = Bookstore<Book, Movie>;
MyBookstore bookstore{ cBook, movieBond };
Book csharpBook{ "C#", "Anders Hejlsberg", 21.99, 8 };
bookstore.addMedia(csharpBook);
Movie movieTarantino{ "Once upon a time in Hollywood", "Quentin Tarantino", 6.99, 3 };
bookstore.addMediaEx(movieTarantino);
std::size_t count{ bookstore.count() };
std::println("Count of elements in Bookstore: {}", count);
}
static void test_bookstore_type_erasure_03() {
std::println("Benchmark - Method Call - using Type Erasure");
Book cBook{ "C", "Dennis Ritchie", 11.99, 12 };
ScopedTimer watch{};
double total{};
for (std::size_t i{}; i != MaxIterations; ++i) {
total += cBook.getCount() * cBook.getPrice();
}
std::print("Done: ");
}
static void test_bookstore_type_erasure_04() {
std::println("Benchmark - Iterating a Container of std:variants - using Type Erasure");
Bookstore<Book, Movie> bookstore{ };
Book cBook{ "C", "Dennis Ritchie", 11.99, 12 };
for (std::size_t i{}; i != 100; ++i) {
bookstore.addMedia(cBook);
}
ScopedTimer watch{};
double total{};
for (std::size_t i{}; i != MaxIterations; ++i) {
double totalBalance{ bookstore.totalBalance() };
total += totalBalance;
}
std::print("Done: ");
}
class BluRay
{
public:
BluRay() = default;
// getter / setter
std::size_t getCount() const { return 0; }
double getPrice() const { return 0.0; } // put into comments
};
static void test_bookstore_type_erasure_05() {
// verifying concept 'MediaConcept'
Bookstore<Book, BluRay, Movie> bookstore{};
}
}
// =====================================================================================
void main_type_erasure()
{
using namespace TypeErasureUsingDynamicPolymorphism;
using namespace TypeErasureUsingTemplateTechniques;
using namespace TypeErasureUsingTemplateTechniquesAndConcepts;
using namespace BookStoreUsingDynamicPolymorphism;
using namespace BookStoreUsingTypeErasure;
TypeErasureUsingDynamicPolymorphism::test_type_erasure_using_dynamic_polymorphism();
TypeErasureUsingTemplateTechniques::test_type_erasure_using_template_techniques();
TypeErasureUsingTemplateTechniquesAndConcepts::test_type_erasure_using_template_techniques();
BookStoreUsingDynamicPolymorphism::test_bookstore_polymorphic_01();
BookStoreUsingDynamicPolymorphism::test_bookstore_polymorphic_02();
BookStoreUsingDynamicPolymorphism::test_bookstore_polymorphic_03();
BookStoreUsingDynamicPolymorphism::test_bookstore_polymorphic_04();
BookStoreUsingTypeErasure::test_bookstore_type_erasure_01();
BookStoreUsingTypeErasure::test_bookstore_type_erasure_02();
BookStoreUsingTypeErasure::test_bookstore_type_erasure_03();
BookStoreUsingTypeErasure::test_bookstore_type_erasure_04();
}
// =====================================================================================
// End-of-File
// =====================================================================================