Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Last active January 4, 2017 14:42
Show Gist options
  • Save daniel-j-h/a1272431c54fcc018cff to your computer and use it in GitHub Desktop.
Save daniel-j-h/a1272431c54fcc018cff to your computer and use it in GitHub Desktop.
Adapter Pattern for templated base class using private inheritance
// Suppose we have a templated framework and we want to adapt its interface -> use the adapter pattern.
// Our templated framework with awkward get_t and set_t member functions:
template <typename T>
class Framework {
public:
Framework(T t = {}) : t_{std::move(t)} { }
T get_t() const { return t_; }
void set_t(T t) { t_ = std::move(t); }
private:
T t_;
};
// Now this is how we implement the adapter pattern:
template <typename T>
class Adapter : private Framework<T> {
public:
using Framework<T>::Framework; // inherit ctors
T get() const { return Framework<T>::get_t(); }
void set(T t) { Framework<T>::set_t(std::move(t)); }
};
// Private inheritance in order to hide the framework's interface; adapt and delegate to templated base class member functions
int main() {
// Now instead of the framework's interface:
Framework<std::string> f;
f.set_t("hello");
std::cout << f.get_t() << std::endl;
// We simply use the adapter
Adapter<std::string> a;
a.set("hello");
std::cout << a.get() << std::endl;
}
// Disclaimer: this is actually one of the few situations where private inheritance is quite nice.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment