Skip to content

Commit 6d17d10

Browse files
bansan85Vincent Legarrec
andauthored
T.5: Add an example for Type erasure (isocpp#1625)
Based on : https://www.modernescpp.com/index.php/c-core-guidelines-type-erasure-with-templates Co-authored-by: Vincent Legarrec <vincent.legarrec@csdental.com>
1 parent d4e2281 commit 6d17d10

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

CppCoreGuidelines.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16829,6 +16829,47 @@ Static helps dynamic: Use static polymorphism to implement dynamically polymorph
1682916829
Dynamic helps static: Offer a generic, comfortable, statically bound interface, but internally dispatch dynamically, so you offer a uniform object layout.
1683016830
Examples include type erasure as with `std::shared_ptr`'s deleter (but [don't overuse type erasure](#Rt-erasure)).
1683116831

16832+
#include <memory>
16833+
16834+
class Object {
16835+
public:
16836+
template<typename T>
16837+
Object(T&& obj)
16838+
: concept_(std::make_shared<ConcreteCommand<T>>(std::forward<T>(obj))) {}
16839+
16840+
int get_id() const { return concept_->get_id(); }
16841+
16842+
private:
16843+
struct Command {
16844+
virtual ~Command() {}
16845+
virtual int get_id() const = 0;
16846+
};
16847+
16848+
template<typename T>
16849+
struct ConcreteCommand final : Command {
16850+
ConcreteCommand(T&& obj) noexcept : object_(std::forward<T>(obj)) {}
16851+
int get_id() const final { return object_.get_id(); }
16852+
16853+
private:
16854+
T object_;
16855+
};
16856+
16857+
std::shared_ptr<Command> concept_;
16858+
};
16859+
16860+
class Bar {
16861+
public:
16862+
int get_id() const { return 1; }
16863+
};
16864+
16865+
struct Foo {
16866+
public:
16867+
int get_id() const { return 2; }
16868+
};
16869+
16870+
Object o(Bar{});
16871+
Object o2(Foo{});
16872+
1683216873
##### Note
1683316874

1683416875
In a class template, non-virtual functions are only instantiated if they're used -- but virtual functions are instantiated every time.

0 commit comments

Comments
 (0)