简体   繁体   English

抽象 class 通过模板化虚拟 function 访问实现的类型?

[英]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.

相关问题 抽象类:成员函数&#39;virtual ...&#39;的抽象返回类型无效 - Abstract class : invalid abstract return type for member function ‘virtual…’ 返回类型为基类/派生类型的抽象类中的纯虚函数 - Pure virtual function in abstract class with return type of base/derived type 调用在基本抽象 class 内的接口中声明为虚拟(并在派生类中实现)的 function - Calling function that was declared virtual in interface (and implemented in derived class) inside base abstract class 错误:尽管实现了所有虚函数,但仍“分配抽象类类型的对象” - Error: "Allocating an object of abstract class type" despite all virtual functions being implemented 抽象类类型…不允许,不能覆盖纯虚函数 - abstract class type … is not allowed, pure virtual function is not override 如何在STL容器中存储具有抽象模板类型的抽象模板类? - How to store an abstract templated class with an abstract template type in STL container? 纯虚函数和抽象类 - pure virtual function and abstract class 通过指针访问虚拟类 - Accessing virtual class through the pointer 在执行SFINAE时访问模板化派生类(CRTP)的静态函数时类型不完整 - Incomplete type while accessing templated derived class (CRTP)' static function while doing SFINAE 成员函数的模板化类和类型返回类型 - Templated class and type return type for a member function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM