How do you override a base templatized class method (that is, a template class with a non-template method) in a child?
#include <Windows.h>
#include <iostream>
struct S{};
template <typename T>
class Base
{
public:
Base()
{
Init(); // Needs to call child
}
virtual void Init() = 0; // Does not work - tried everything
// - Pure virtual
// - Method/function template
// - Base class '_Base' which Base extends that has
// pure virtual 'Init()'
// - Empty method body
};
class Child : public virtual Base<S>
{
public:
virtual void Init()
{
printf("test"); // Never gets called
}
};
int main()
{
Child foo; // Should print "test"
system("pause");
return 0;
}
I know the technique to pass the child class type as a template argument to the base class and then use a static_cast, but it’s just so unclean to me for something that should be incredibly easy.
I’m sure there is some fundamental idea behind templates that I am just not grasping, because I’ve been searching for hours and can’t find any code or solutions to this particular scenario.
Calling
virtualmethods from constructors is a bad idea, as it doesn’t get the behavior you expect. When the constructor ofBaseexecutes, the object is not yet fully constructed and is not yet aChild.Calling it outside the constructor would work.