Created
November 24, 2021 17:24
-
-
Save dyigitpolat/129c8717e366a594a31d17ab2b64da90 to your computer and use it in GitHub Desktop.
type erasure demo
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
#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