Last active
August 18, 2016 15:11
-
-
Save nikhedonia/58e658226ea6c655d859395a56e1bb4c to your computer and use it in GitHub Desktop.
Gist created by https://fiddle.jyt.io
This file contains 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
// Type Erasure | |
// https://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil | |
// https://akrzemi1.wordpress.com/2013/11/18/type-erasure-part-i/ | |
#include<memory> | |
#include<iostream> | |
struct Printable { | |
struct Concept { | |
virtual void print()=0; | |
}; | |
template<class T> | |
struct Model : Concept { | |
T model; | |
Model(T m): model{m}{} | |
virtual void print(){ model.print(); } | |
}; | |
template<class T> | |
Printable(T const& printable) | |
: pimpl{ new Model<T>(printable) } | |
{} | |
void print(){ pimpl->print(); } | |
std::unique_ptr<Concept> pimpl; | |
}; | |
struct Number { | |
int x; | |
void print() const { std::cout << x << std::endl; } | |
}; | |
struct Vector { | |
int x; | |
int y; | |
void print() const { std::cout << "("<<x <<"|"<<y<<")"<< std::endl; } | |
}; | |
void printMe(Printable x) { | |
x.print(); | |
} | |
// printMe(Number{3}) | |
// printMe(Vector{3,4}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment