Puppy
Puppy

Reputation: 146940

Can specializations of a template function be virtual?

Something like, for example,

class A {
    template<typename T> T DoStuff();
    template<> virtual int DoStuff<int>() = 0;
};

Visual Studio 2010 says no, but I get a funny feeling that I simply messed up the syntax. Can explicit full specializations of a member function template be virtual?

Upvotes: 5

Views: 704

Answers (3)

Explicit specializations aren't legal within a class. Even if you could make it a partial specialization you would still run into the "templates can't be virtual" problem.

n3290, § 14.5.2 states:

A member function template shall not be virtual.

And gives this example:

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

Before going on to state that member function templates do not count for virtual overrides too.

Upvotes: 8

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

You can get a similar effect by overloading your function template with a regular non-template virtual function.

Upvotes: 0

ks1322
ks1322

Reputation: 35736

According to C++98 Standard member function template shall not be virtual. http://www.kuzbass.ru:8086/docs/isocpp/template.html.

-3- A member function template shall not be virtual. [Example:

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

Upvotes: 2

Related Questions