Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override template member in Interface

Tags:

c++

templates

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.

like image 872
tea2code Avatar asked Mar 15 '14 10:03

tea2code


1 Answers

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:

  • Change design (recommended)
  • Follow another approach e.g. multimethod by Andrei Alexandrescu (http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html)
like image 188
Marco A. Avatar answered Oct 25 '22 00:10

Marco A.