Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c++ - 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;
}

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.

question from:https://stackoverflow.com/questions/65944348/how-to-override-a-templated-function-from-non-templated-parent-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Your functions, in order to be polymorphic, should be marked with virtual

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...