覆盖接口中的模板成员 [英] Override template member in Interface

查看:54
本文介绍了覆盖接口中的模板成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用我可以在派生类中覆盖的模板方法声明某种类型的基类?以下示例:

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:

  • Change design (recommended)
  • Follow another approach e.g. multimethod by Andrei Alexandrescu (http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html)

这篇关于覆盖接口中的模板成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆