覆盖接口中的模板成员 [英] Override template member in Interface
问题描述
是否可以使用我可以在派生类中覆盖的模板方法声明某种类型的基类?以下示例:
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example:
#include <iostream>
#include <stdexcept>
#include <string>
class Base
{
public:
template<typename T>
std::string method() { return "Base"; }
};
class Derived : public Base
{
public:
template<typename T>
std::string method() override { return "Derived"; }
};
int main()
{
Base *b = new Derived();
std::cout << b->method<bool>() << std::endl;
return 0;
}
我希望派生
作为输出,但它是 Base
。我认为有必要制作一个模板包装器类,该类将实现类作为模板参数接收。但是我想确定。
I would expect Derived
as the output but it is Base
. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
推荐答案
1)为了实现多态,您的函数应标有 virtual
1) Your functions, in order to be polymorphic, should be marked with virtual
2)模板化函数在POI上实例化并且不能是虚拟的(签名是什么?您保留多少个vtable条目? )。 模板函数是一种编译时机制,虚拟函数是一种运行时机制。
2) Templated functions are instantiated at the POI and can't be virtual (what is the signature??How many vtable entries do you reserve?). Templated functions are a compile-time mechanism, virtual functions a runtime one.
某些可能的解决方案涉及:
Some possible solutions involve:
- 更改设计(推荐)
- 遵循另一种方法,例如多方法,由Andrei Alexandrescu( http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11。 html )
- Change design (recommended)
- Follow another approach e.g. multimethod by Andrei Alexandrescu (http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html)
这篇关于覆盖接口中的模板成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!