Specializing method of class template?

Started by
5 comments, last by Waterlimon 12 years, 2 months ago
Lets say i have a class like:

template <class T,int Num>
class Test
{
public:
T Method() const
{
return 9001;
}
};



How would i create a specialization for
template <int Num>
int Test<int,Num>::Method() const
{
return 8999;
}


Because currently it throws "unable to match function definition to an existing declaration" at me whatever way i try to do it.

Basically i want to have Method run different code if the first template parameter of Test is int

Thx

o3o

Advertisement

template<class T, int Num>
struct Test
{
int Method() const {
return 2;
}
};
template<int Num>
struct Test<int, Num>
{
int Method() const {
return 42;
}
};
#include <iostream>
int main() {
std::cout<<Test<int, 4>().Method()<<std::endl;
std::cout<<Test<float, 4>().Method()<<std::endl;
}

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

But if i have 100 other methods which will not need changing, do i need to copypasta those too? Or just the stuff that needs specialization?

o3o


But if i have 100 other methods which will not need changing, do i need to copypasta those too? Or just the stuff that needs specialization?

The former.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

There are hacks to get around needing to redefine every member function. For example, you can put all the functions that don't need changing in a base class and create a derived class just for the functions that need specialization.
What sometimes works is inheriting the specialization in.

template<class T>
class MethodHelper {
public:
int method() { return 0; }
};

template<>
class MethodHelper<int> {
public:
int method() { return 42; }
};

template<class T>
class MyClass : MethodHelper<T> {
//...
};



alternatively you can make MethodHelper a private member and forward your method to it.
Thanks, that should work...

o3o

This topic is closed to new replies.

Advertisement