Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template specialization in derived class

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

like image 373
Surya Avatar asked Dec 18 '09 13:12

Surya


2 Answers

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.

like image 78
Adam Bowen Avatar answered Sep 28 '22 04:09

Adam Bowen


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.

like image 37
Andreas Brinck Avatar answered Sep 28 '22 04:09

Andreas Brinck