Created
November 2, 2025 03:55
-
-
Save harrisonturton/41adfbe47f63920dcf43a0714a34f86b to your computer and use it in GitHub Desktop.
C++ type erasure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| /** | |
| * Concept enforcing values on the templated types. Clients are not exposed to this. | |
| */ | |
| template <typename T> | |
| concept ToBeErased = requires(T a) { | |
| { a.doSomething() } -> std::convertible_to<void>; | |
| }; | |
| /** | |
| * Type-erased wrapper over templated types. | |
| */ | |
| class Erased { | |
| public: | |
| /** | |
| * Erase the type of a concrete template instance. | |
| */ | |
| template <ToBeErased T> | |
| explicit Wrapper(T obj) | |
| : impl_(std::make_unique<Model<T>>(std::move(obj))) {} | |
| /** | |
| * Invoke a function on the templated instance. | |
| */ | |
| void doSomething() { | |
| obj_->doSomething(); | |
| } | |
| private: | |
| struct Interface { | |
| virtual ~Interface() = default; | |
| virtual void DoSomething() = 0; | |
| }; | |
| template <typename T> | |
| struct Model final : Interface { | |
| Model(T obj) | |
| : obj_(std::move(obj)) {} | |
| void doSomething() override { | |
| obj_.doSomething(); | |
| } | |
| T obj_; | |
| }; | |
| std::unique_ptr<Interface> obj_; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment