1

I've read over the web that template virtual functions are not allowed , is it true ? It's a little bit weird since this code compile great on my Eclipse's g++

template <class T>
class A {

public:
    virtual ~A<T>() { }
    virtual void printMe() {cout << "I am A class" << endl;}
};

template <class T>
class B: public A<T> {

public:
    void printMe() {cout << "I am B class" << endl;}
};

int main() {

    A<int> * ptr = new B<int>;
    ptr->printMe();
    delete ptr;
    return 0;
}

Regards,Ronen

Stuart Cook
  • 3,994
  • 25
  • 23
Ron_s
  • 1,429
  • 1
  • 14
  • 24
  • Here : http://stackoverflow.com/questions/2354210/can-a-member-function-template-be-virtual – Ron_s Aug 27 '11 at 06:23

2 Answers2

3

virtual methods in a template type (as seen in your example) is valid.

the restriction you refer to takes this form:

class type {
  //...
  template <typename T> virtual void r() const;
};
justin
  • 104,054
  • 14
  • 179
  • 226
  • Then what you're saying is that template and virtual function doesn't exist in c++ ? what might be the reason ? dynamic binding for virtual and early binding for template ? they do not mix ? – Ron_s Aug 27 '11 at 06:22
  • see David's excellent answer here: http://stackoverflow.com/questions/757270/is-making-a-function-template-specialization-virtual-legal – justin Aug 27 '11 at 06:26
  • just to see that I got it right , what David is actually saying is that every virtual function has its own address stored in the vtable.Now,a template method would be declared only after we've decided on its type .If we have a few different types to the method f() , then we would have the same function in different places in the memory , and the compiler won't know which one to choose ? – Ron_s Aug 27 '11 at 06:51
  • close. there really is no problem with the compiler knowing which to choose -- I would expect such an implementation to simply use the 'One Definition Rule'. the core of the problem is that it would force vtables to become mutable at runtime, and significantly change object initialization and dispatch of virtual calls. a vtable in its current form can be considered immutable and always proper initialization is guaranteed. (cont) – justin Aug 27 '11 at 07:23
  • (cont) allowing mutations would introduce a lot of changes. it's possible to safely implement mutations, but that comes at a cost which (i believe) many c++ devs would dislike. it would add a lot of overhead to what is a very fast dynamic dispatch, and dynamic dispatch would no longer be constant time. additionally, a few language/runtime extensions would be required to implement this. fortunately, there are enough language features that this isn't a typical problem for most programs. – justin Aug 27 '11 at 07:23
0

What you have here is not a template virtual function, but rather a template class containing a ordinary virtual function.

As you have found, that is perfectly fine.

Stuart Cook
  • 3,994
  • 25
  • 23