[英]Abstract class accessing the implemented type through a templated virtual function?
I was wondering if there could be any way to write a template function in an abstract class, and have it (the template function) automatically instantiated with the type of the derived class?我想知道是否有任何方法可以在抽象 class 中编写模板 function,并使用派生的 class 的类型自动实例化它(模板函数)?
So you have a class that looks something like this所以你有一个看起来像这样的 class
class A
{
virtual template < typename T>
void vtfunc(void)
};
class B : public A
{
/// No declared members pertaining to this example
}
Then, whenever a class derived from A is declared, it compiles "vtfunc" with itself as the template parameter T. Then, calling vtfunc() through an interface of A calls the isntance of that function compiled for its derived class B.然后,每当声明从 A 派生的 class 时,它就会以自身作为模板参数 T 来编译“vtfunc”。然后,通过 A 的接口调用 vtfunc() 调用为其派生的 ZA2F22ED4F8EBC14ZDC4 编译的 functionDC4 的实例。
Is there any way of doing this, or writing something fiddley that have this effect?有没有办法做到这一点,或者写一些有这种效果的东西?
Obviously I am aware that the template parameter could only affect the internals of the class, and not the return type and parameters - they would need to be the same because of the way polymorphism works.显然我知道模板参数只能影响 class 的内部,而不是返回类型和参数——由于多态性的工作方式,它们需要相同。
I'm not sure what you're after but one common pattern is the so-called curiously recurring template pattern ;我不确定你在追求什么,但一种常见的模式是所谓的奇怪重复的模板模式; here, the base class itself is the template, not its member functions.
在这里,基础 class 本身是模板,而不是它的成员函数。 In other words:
换句话说:
template <typename T>
class A
{
virtual void vtfunc(void)
};
class B : public A<B>
{
…
};
Consider using a non-member function instead.考虑改用非成员 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.