Salt_Peter
11/4/2008 4:21:00 AM
On Nov 3, 7:22 pm, "(2b|!2b)==?" <void-s...@ursa-major.com> wrote:
> I have a class template. Each of the instantiations implements a method
> in the class template differently, so I (need?) to use template
> speciaization.
>
> My question is this, when writing the specialization, do I need to
> implement only the method that is 'different', or do I need to implement
> all the methods in the class template?
>
> template <typename T1, typename T2>
> class MyClass
> {
public:
> void foo(const T1&, T2&) const;
> ...
> //other methods follow below
> int foobar(T1, T1, T2&);
> // ...etc
>
> };
>
> template<>
> class MyClass<int,double>
> {
public:
> void foo(const int& i, double& d) const
> {
> //'specialized' logic here
> }
>
> /* Do I need all the other methods here ?
> .... */
>
>
>
> };
Yes, You'll need to provide specialization for the entire type.
To partially specialize a template, derive from the generic one:
class DerivedClass : public MyClass< int, double >
{
public:
void foo(const int& i, double& d) const
{
// do specialized stuff here
}
};
foo(...) now overides any foo(...) in the base class and foobar() is
available.
This works too:
template< typename N = int, typename D = double >
class DerivedClass : public MyClass< N, D >
{
public:
void foo(const N& i, D& d) const
{
std::cout << "DerivedClass::foo(const int&, double&) const\n";
}
};
DerivedClass< > instance;
instance.foobar(...);