Last active
January 12, 2018 22:17
-
-
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
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A nice perk is that the greeter class can live in another header file, unaware of derived classes.