Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.