Skip to content

Instantly share code, notes, and snippets.

@dyigitpolat
Created November 24, 2021 17:24
Show Gist options
  • Save dyigitpolat/129c8717e366a594a31d17ab2b64da90 to your computer and use it in GitHub Desktop.
Save dyigitpolat/129c8717e366a594a31d17ab2b64da90 to your computer and use it in GitHub Desktop.
type erasure demo
#include <iostream>
#include <vector>
#include <memory>
template <typename T>
void concrete_impl(const T& t)
{
std::cout << "concrete implementation \n";
}
class Interface {
public:
template <typename T>
Interface(const T& x) : mptr{new Model<T>(x)} {}
Interface(const Interface& x) : mptr{x.mptr->clone()} {}
friend void common_interface(const Interface& i)
{
std::cout << "common interface \n";
i.mptr->virtual_impl();
}
private:
struct Concept {
virtual ~Concept() = default;
virtual void virtual_impl() const = 0;
virtual std::unique_ptr<Concept> clone() const = 0;
};
template <typename T>
struct Model final : Concept {
Model(const T& x) : mx{x} {}
std::unique_ptr<Concept> clone() const override
{
return std::make_unique<Model>(*this);
}
void virtual_impl() const override
{
concrete_impl(mx);
}
T mx;
};
std::unique_ptr<Concept> mptr;
};
struct A {
};
struct B {
};
int main() {
std::vector<Interface> vec;
vec.push_back(A{});
vec.push_back(B{});
for( auto a : vec)
{
common_interface(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment