Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 635
Puppy Avatar asked Oct 02 '11 18:10

Puppy


People also ask

Can template functions be virtual?

No, template member functions cannot be virtual.

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.

What is function template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

Can you partially specialize a C++ function template?

You can choose to specialize only some of the parameters of a class template. This is known as partial specialization. Note that function templates cannot be partially specialized; use overloading to achieve the same effect.


2 Answers

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.

like image 175
Flexo Avatar answered Oct 18 '22 06:10

Flexo


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
};
like image 41
ks1322 Avatar answered Oct 18 '22 06:10

ks1322