Skip to content

Instantly share code, notes, and snippets.

@harrisonturton
Created November 2, 2025 03:55
Show Gist options
  • Select an option

  • Save harrisonturton/41adfbe47f63920dcf43a0714a34f86b to your computer and use it in GitHub Desktop.

Select an option

Save harrisonturton/41adfbe47f63920dcf43a0714a34f86b to your computer and use it in GitHub Desktop.
C++ type erasure
#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