views:

138

answers:

4

Hello all,

I've a base class with a function template.

I derive from base class and try to have a specialization for the function template in derived class

I did something like this.

class Base 
{
..
template <typename T>
fun (T arg) { ... }

};

class Derived : public Base
{
...
} ;

template <>
Derived::fun(int arg);

and in .cpp file I've provided implementation for the template specialization.

This works fine with MSVC 8.0 and g++-4.4.2 complains about lack of function declaration fun in Derived class.

I do not know which compiler is behaving correctly. Any help in this is greatly appreciated.

Thanks in advance, Surya

+1  A: 

Why can't you do

template <>
Base::fun(int arg);

g++'s error message looks right to me. fun is declared in Base and not in Derived.

Andreas Brinck
+3  A: 

You need to declare the function in Derived in order to be able to overload it:

class Derived : public Base
{
    template <typename T>
    void fun (T arg) 
    {
        Base::fun<T>(arg);
    }

} ;

template <>
void Derived::fun<int>(int arg)
{
    // ...
}

Note that you may need to inline the specialisation or move it to an implementation file, in which case you must prototype the specialisation in the header file as:

template <>
void Derived::fun<int>(int arg);

otherwise the compiler will use the generalised version of 'fun' to generate code when it is called instead of linking to the specialisation.

Adam Bowen
A: 
ltcmelo
A: 

g++ behaves correctly, because fun is defined in Base.

Wolfgang Plaschg