Why does TemplateChild in the following code not work? I know that virtual methods cannot be templates, but why can explicitly-instantiated template methods not override virtual methods?
#include <iostream>
class VirtBase
{
public:
VirtBase() {};
virtual ~VirtBase() {};
virtual void method( int input ) = 0;
virtual void method( float input ) = 0;
};
class RegularChild : public VirtBase
{
public:
RegularChild() {};
~RegularChild() {};
void method( int input ) {
std::cout << "R" << input << std::endl;
}
void method( float input ) {
std::cout << "R" << input << std::endl;
}
};
class TemplateBounceChild : public VirtBase
{
public:
TemplateBounceChild() {};
~TemplateBounceChild() {};
void method( int input ) {
this->method<>( input );
}
void method( float input ) {
this->method<>( input );
}
template< typename INPUT >
void method( INPUT input ) {
std::cout << "B" << input << std::endl;
};
};
class TemplateChild : public VirtBase
{
public:
TemplateChild() {};
~TemplateChild() {};
template< typename INPUT >
void method( INPUT input ) {
std::cout << "T" << input << std::endl;
};
};
template void TemplateChild::method< int >( int );
template void TemplateChild::method< float >( float );
int main( int, char**, char** )
{
int i = 1;
float f = 2.5f;
VirtBase * v;
RegularChild r;
v = &r;
r.method( i );
r.method( f );
v->method( i );
v->method( f );
TemplateChild c; // TemplateBounceChild here works correctly.
v = &c;
c.method( i );
c.method( f );
v->method( i );
v->method( f );
return 0;
}
gcc 4.4.7 (CentOS 6) and Clang 3.3 (trunk 177401) agree that the two pure virtual methods are not implemented in TemplateChild, although at this point in the compilation TemplateChild explicitly has a method named 'method' that takes a float, and a method named 'method' that takes an int.
Is it just because the explicit instantiation has come too late for TemplateChild to be considered non-pure virtual?
Edit: C++11 14.5.2 [temp.mem]/4 says that this isn't allowed for specialisations. But I can't find anything so clear in the [temp.explicit] section for the same thing.
4 A specialization of a member function template does not override a virtual function from a base class.
I also edited TemplateBounceChild to match the example used in that section of the C++11 draft.
Because the Standard Says So. See C++11 14.5.2 [temp.mem]/3: