简体   繁体   中英

Base class pure virtual functions with templated derived class

I am attempting to use polymorphism with a templated derived class. Consider the following code:

// base class
class A {
  public:
  virtual void f() = 0;
};

// templated derived class
template< typename T >
class B : public A {};

template <> //define a specialization of B
class B< int > {};

// trying to define a specialization of f
template <>
void B< int >::f() {}

My base class has the pure virtual function f . I am storing a vector of base class pointers A* and would like to call f on all of them, with appropriate polymorphism on the templated derived class. However, I am unable to define specializations of f, as I receive the following error:

test.cpp:17:18: error: no member function ‘f’ declared in ‘B<int>’ void B< int >::f() {}

Obviously the error here is that f is not actually a member function of the templated class. Is there any way to define specializations of f (or something nearly equivalent), or is this simply not possible? If it is not possible, can you suggest another approach?

[Apologies if this is a duplicate--I searched and found many variations of questions on templating, inheritance, and polymorphism, but none that exactly matched mine.]

template <> //define a specialization of B
class B< int > {};

Your specialization does not define the overriden virtual function. Change this specialization to:

template <> //define a specialization of B
class B< int > : public A
{
  public:
      void f() override;
}

A specialization is like defining a new class. You have to define everything that's in it. If the specialization should have a particular method: define it.

EDIT: also corrected the typo inherited from the original question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM