Jump to content
  • Advertisement
Sign in to follow this  
Waterlimon

Specializing method of class template?

This topic is 2498 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!