Last active
November 24, 2021 17:55
-
-
Save dyigitpolat/04a77c221859c46de8b571b8515f927f to your computer and use it in GitHub Desktop.
generic type erasure mechanism 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 Common> | |
class I { | |
public: | |
template <typename T> | |
I(const T& x) : mptr{new Model<T>(x)} {} | |
I(const I& x) : mptr{x.mptr->clone()} {} | |
void common() | |
{ | |
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 | |
{ | |
Common::impl(mx); | |
} | |
T mx; | |
}; | |
std::unique_ptr<Concept> mptr; | |
}; | |
struct A { | |
int ival; | |
void print() | |
{ | |
std::cout << ival << " "; | |
} | |
}; | |
struct B { | |
double dval; | |
void print() | |
{ | |
std::cout << dval << " "; | |
} | |
}; | |
struct Printable | |
{ | |
template <typename T> | |
static void impl(T t) | |
{ | |
t.print(); | |
} | |
}; | |
int main() { | |
std::vector<I<Printable>> vec; | |
vec.push_back(A{56}); | |
vec.push_back(B{1.2}); | |
for( auto a : vec) | |
{ | |
a.common(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment