I have a class Foo which uses CRTP to inherit a template method from a parent class and avoid having to provide literally dozens of individual member methods. Something like this:
class Foo : public SomeBarClass<Foo>
{
//..
//from SomeBarClass
public:
template <class T> void onMsg(T* msg);
private:
IFoxMod* foxMod_;
};
Now, in the implementation for onMsg, I would like something like this:
template <class T>
void Foo::onMsg(T* msg)
{
if (foxMod_->shouldDoStuff(msg))
{
//do stuff
}
}
and there can be many foxMod_ types (one of them instantiated in the Foo constructor by name given in config file) as long as they abide by the common interface of providing a bool shouldDoStuff method. The problem, is that this leads me to define the following:
struct IFoxMod
{
virtual ~IFoxMod() {}
template <class T> shouldDoStuff(T* msg) = 0;
};
for all of the FoxMods to implement (like, class redMountainLogic : public IFoxMod might have it’s own way of discerning, when it is appropiate to do stuff).
This is illegal though because one cannot have virtual templates and I’m trying to find a workaround for it. Basically, I need to have dynamic dispatch, but the argument I am passing is a template. I can’t think of a workaround.
Virtual function tables don’t seem to get along well with template specializations. Not too surprising. VFTs are generally based on declaration order, which doesn’t really exist with templates. One solution is to manually recreate VFTs.
Here’s an example. It could probably be a little cleaner, but it works.