From 6d17d10604b57bd6e45ce5f234eb5a2719a18a1e Mon Sep 17 00:00:00 2001 From: LE GARREC Vincent Date: Wed, 29 Jul 2020 18:37:01 +0200 Subject: [PATCH] T.5: Add an example for Type erasure (#1625) Based on : https://www.modernescpp.com/index.php/c-core-guidelines-type-erasure-with-templates Co-authored-by: Vincent Legarrec --- CppCoreGuidelines.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index b9d08fd..391ec4d 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -16829,6 +16829,47 @@ Static helps dynamic: Use static polymorphism to implement dynamically polymorph Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout. Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)). + #include + + class Object { + public: + template + Object(T&& obj) + : concept_(std::make_shared>(std::forward(obj))) {} + + int get_id() const { return concept_->get_id(); } + + private: + struct Command { + virtual ~Command() {} + virtual int get_id() const = 0; + }; + + template + struct ConcreteCommand final : Command { + ConcreteCommand(T&& obj) noexcept : object_(std::forward(obj)) {} + int get_id() const final { return object_.get_id(); } + + private: + T object_; + }; + + std::shared_ptr concept_; + }; + + class Bar { + public: + int get_id() const { return 1; } + }; + + struct Foo { + public: + int get_id() const { return 2; } + }; + + Object o(Bar{}); + Object o2(Foo{}); + ##### Note In a class template, non-virtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.