12

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

4 Answers 4

7

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.

2
  • What is wrong with what Surya was trying to do? I tried it myself and it does not compile. But I can't understand the reason why?
    – RLT
    Commented Sep 22, 2011 at 12:11
  • 1
    In Surya's version there is no function called "Derived::fun", there is only "Base::fun", so you can't specialised "Derived::fun".
    – Adam Bowen
    Commented Sep 22, 2011 at 12:16
1

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.

0

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

0

Also, an alternative option would be a plain non-template function in Derived...


class Derived : public Base
{
public:
  void fun(int) { /* ... */ }
};

1
  • No so simple, that would hide Base::fun.
    – YvesgereY
    Commented Mar 5, 2014 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.