Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual methods and template classes

I got over a problem, I think a very specific one.

I've got 2 classes, a B aseclass and a D erived class (from B aseclass). B is a template class ( or class template) and has a pure virtual method virtual void work(const T &dummy) = 0; The D erived class is supposed to reimplement this, but as D is Derived from B rather than D being another template class, the compiler spits at me that virtual functions and templates don't work at once.

Any ideas how to accomplish what I want?

I am thankfull for any thoughts and Ideas, especially if you allready worked out that problem

this class is fixed aka AS IS, I can not edit this without breaking existing code base

template <typename T>
class B {
public:
...
virtual void work(const T &dummy) = 0;
..
};

take int* as an example

class D : public B<int*>{
...
virtual void work(const int* &dummy){ /* put work code here */ }
..
};

Edit: The compiler tells me, that void B<T>::work(const T&) [with T = int*] is pure virtual within D

like image 658
drahnr Avatar asked Mar 27 '10 21:03

drahnr


People also ask

Can template class have virtual function?

A class template can indeed contain virtual or pure virtual functions. This was employed by Andrei Alexandresu in "Modern C++ Design" to implement the visitor pattern using templates and type lists.

What are virtual methods?

What Does Virtual Method Mean? A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.

What is a template class?

As per the standard definition, a template class in C++ is a class that allows the programmer to operate with generic data types. This allows the class to be used on many different data types as per the requirements without the need of being re-written for each type.

What is the difference between a template and a class?

An individual class defines how a group of objects can be constructed, while a class template defines how a group of classes can be generated. Note the distinction between the terms class template and template class: Class template.


1 Answers

You placed the const in the wrong place. Try

virtual void work(int* const &dummy){ /* put work code here */ }

const int* is the same as int const*, i.e. it associates the const with the int and not the pointer.

like image 118
Rüdiger Hanke Avatar answered Oct 05 '22 22:10

Rüdiger Hanke