Reputation: 1197
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
Upvotes: 12
Views: 11402
Reputation: 4032
Also, an alternative option would be a plain non-template function in Derived...
class Derived : public Base
{
public:
void fun(int) { /* ... */ }
};
Upvotes: 0
Reputation: 11240
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.
Upvotes: 7
Reputation: 52549
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
.
Upvotes: 1