Skip to content

Instantly share code, notes, and snippets.

@jg-you
Last active January 12, 2018 22:17
Show Gist options
  • Save jg-you/79b9c37ffa92576caf0d7582c921f2de to your computer and use it in GitHub Desktop.
Save jg-you/79b9c37ffa92576caf0d7582c921f2de to your computer and use it in GitHub Desktop.
How to use stateless class derived from a virtual base class in a templated class. A strategy I use in many code
#include <iostream>
class master_virtual
{
public:
virtual void msg() {return;}
};
class derived_hi : public master_virtual
{
public:
void msg() {std::cout << "Hi from derived\n";}
};
class derived_hey : public master_virtual
{
public:
void msg() {std::cout << "Hey from derived\n";}
};
template <class TYPE_A>
class greeter
{
protected:
TYPE_A msg_class;
public:
void greet()
{
msg_class.msg();
}
};
int main(int argc, char const *argv[])
{
greeter<derived_hi> hi;
hi.greet(); // Hi from derived
greeter<derived_hey> hey;
hey.greet(); // Hey from derived
return 0;
}
@jg-you
Copy link
Author

jg-you commented Jun 4, 2017

A nice perk is that the greeter class can live in another header file, unaware of derived classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment