I have the following hierarchy of class:
class Boy : Child
class Girl : Child
template<class T>
class Parent
{
vector<T> children;
}
class AnnaBoys: public Parent<Boy>
{
void ProcessChild() { do things specific to Anna boys };
};
class AnnaGirls: public Parent<Girl>
{
void ProcessChild() { do things specific to Anna girls};
};
The two ProcessChild()
function here are doing unrelated things, not "templetable" in the way add<T>
could be.
I'm looking to avoid having to create two Anna class and just do this instead:
template<class T>
class Anna: public Parent<T>
{
void ProcessChild()
{
if(T is Boys)
ProcessBoys();
else
ProcessGirls();
};
};
Is there any clean way to do this without doing a dynamic_cast at runtime ?
Thanks.
You can specialize individual member functions without specifying the whole class. In this case:
Header:
template<typename T>
class Anna : Parent<T> {
public:
void ProcessChild() {
// default implementation (if desired)
}
};
template<> void Anna<Boy>::ProcessChild();
template<> void Anna<Girl>::ProcessChild();
Source file:
template<> void Anna<Boy>::ProcessChild() {
// implementation for boys
}
template<> void Anna<Girl>::ProcessChild() {
// implementation for girls
}
It is possible to have the specialized member functions in the header by declaring them inline
, if you want to keep things header-only:
template<typename T>
class Anna : Parent<T> {
public:
void ProcessChild() {
// default implementation (if desired)
}
};
template<> inline void Anna<Boy>::ProcessChild() {
// implementation for boys
}
template<> inline void Anna<Girl>::ProcessChild() {
// implementation for girls
}
Thanks to @Deduplicator for spotting that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With