[英]Overriding base template class method
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. 我知道将子类类型作为模板参数传递给基类,然后使用
static_cast
,但是对于我来说这太不干净了,因为它应该非常容易。
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 virtual
methods from constructors is a bad idea, as it doesn't get the behavior you expect. 从构造函数中调用
virtual
方法不是一个好主意,因为它无法获得您期望的行为。 When the constructor of Base
executes, the object is not yet fully constructed and is not yet a Child
. 当
Base
的构造函数执行时,该对象尚未完全构造,并且不是Child
。
Calling it outside the constructor would work. 在构造函数外部调用它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.