Child class template overriding the virtual function of the parent class

The code below compiles with gcc v4.3.3, and the template child class seems to override the virtual function in the parent, but doesn't that break the rule that you cannot have a virtual template function? Or is something else going on that I don't understand?

class BaseClass
{
public:
  virtual void Func(int var)
  {
    std::cout<<"Base int "<<var<<std::endl;
  }

  virtual void Func(double var)
  {
    std::cout<<"Base double "<<var<<std::endl;
  }
};

template <class TT>
class TemplateClass : public BaseClass
{
public:
  using BaseClass::Func;
  virtual void Func(TT var)
  {
    std::cout<<"Child TT "<<var<<std::endl;
  }
};

int main(int argc, char **argv)
{
  BaseClass a;
  TemplateClass<int> b;
  BaseClass *c = new TemplateClass<int>;

  int intVar = 3;
  double doubleVar = 5.5;

  a.Func(intVar);
  a.Func(doubleVar);
  b.Func(intVar);
  b.Func(doubleVar);
  c->Func(intVar);
  c->Func(doubleVar);
  delete c;
}

Then issued:

Base int 3
Base double 5.5
Child TT 3
Base double 5.5
Child TT 3
Base double 5.5

as I hoped, but I'm not sure why it works.

+5
source share
2 answers

A class template can have virtual member functions.

- . :

class C
{
public:
    template <typename T>
    virtual void f();
};

, - , , . , TemplateClass::Func -, ,

template <typename T>
void Func(T var) { /* ... */ }

BaseClass::Func.

+8

. : 14.5.2/4:

- . [:

template <class T> struct AA {
  template <class C> virtual void g(C); // error
  virtual void f(); // OK
};
+2

All Articles