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.