Search code examples
c++templatesvirtualstdvector

Virtual method template in Class template C++


I got small problem with my study's problem.

    template<typename T> 
    class AlgorytmSortujacy 
       { 
       public: 
          template <typename F> 
          virtual std::vector<T> sortuj(std::vector<T>  w, F porownywacz) const = 0;
       }; 

This code has to be interface for sort algorithms. When I e.x. implement bubble sort, I have to derive from this class and implement the sortuj funtion.

The problem is that VS2013 does not accept those form of code, I mean template virtual function (C2898 error). Do you know of any solutions?

As you see, sort function takes container from std::vector and F porownywacz - it's and functional object which compares two elements of an array

At the end - I think I can't change this code, I got it from the teacher and I think I have to make it work.


Solution

  • The problem is with F porownywacz, it can't be a template with the pure virtual function.

    Virtual member functions can't be templates, to quote clang "virtual cannot be specified on member function templates".

    From the cppreference site;

    A member function template cannot be virtual, and a member function template in a derived class cannot override a virtual member function from the base class.

    The distinction here is essentially ascribed to the virtual functions are a "runtime thing," they are resolved at runtime. The template types are required to be resolved at compile time.

    Are you using a conformant complier in the class, what is the teacher using? I would approach you teacher about the issue, quoting the compiler error and to check you are on the same page as your class mates, talk them as well on what error they are getting.


    This Q&A contains more detail and some alternatives you may be interested in.