Skip to content

Instantly share code, notes, and snippets.

@csullivan
Last active October 25, 2017 16:10
Show Gist options
  • Save csullivan/6ed167c9b94a496ba8041b2719790c79 to your computer and use it in GitHub Desktop.
Save csullivan/6ed167c9b94a496ba8041b2719790c79 to your computer and use it in GitHub Desktop.
Example of type erasure with C++ templates
class Base {
public:
Base* interface_method(...) {
// this function could read in a file, and based on a
// a string determine the type that needs to be used
// and then the builder is set using set_builder<T>()
// now, internally you can use builder->build(...) to
// build the child that you want
// however, if you would like to store a different
// specialized container for data, then you will
// need in addition to use the Curiously Recursive
// Template Pattern (CRTP) so that you may define
// methods in a base class which interact with the
// child classes members by name (irrespective of type).
// An example of this can be found in my CRTP gist
// https://gist.github.com/csullivan/8ce2311fa72cdc947958b3db786ac54d#file-crtp-cc-L13
}
private:
template<typename T>
void set_builder() { builder = new Builder_Impl<T>(); }
// helper type erased classes
struct Builder {
virtual Base* build(...) = 0;
};
template<typename Child>
struct Builder_Impl : Builder {
virtual Base* build(...) {
// some function that can make Child objects given the input arguments
return make_derived_class<Child>(...);
}
}
private:
Builder* builder;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment