Sign in to follow this  
smr

How to specialize template for method

Recommended Posts

smr    2468

I am back to C++ after many, many years' absence. I'm trying to create a simple vector class (non-interesting stuff removed):

template <class T>
class Vector3
{
public:
	T length();
public:
	T x, y, z;
};

I want to specialize the length method so that I can select the correct version of sqrt to call based on type of T. The best I can come up with is the following. "Best" is really a misnomer, since it doesn't compile. Can someone enlighten me what the best way to do this would be?


template <>
void Vector3<int>::length()
{
	return (T) sqrtl((long)(this->x * this->x) + (long)(this->y * this->y) + (long)(this->z * this->z));
}
template <>
void Vector3<long>::length()
{
	return (T) sqrtl((this->x * this->x) + (this->y * this->y) + (this->z * this->z));
}
template <>
void Vector3<float>::length()
{
	return (T) sqrtf((this->x * this->x) + (this->y * this->y) + (this->z * this->z));
}
template <>
void Vector3<double>::length()
{
	return (T) sqrt((this->x * this->x) + (this->y * this->y) + (this->z * this->z));
}
template <class T>
T Vector3<T>::length()
{
	return (T) sqrt((double)(this->x * this->x) + (double)(this->y * this->y) + (double)(this->z * this->z));
}

Thanks in advance!

 

Signed,

Clueless about C++

Share this post


Link to post
Share on other sites
smr    2468

Ah, duh. I figured it out. I have the specializations returning void, and am casting to (T) when it doesn't even know what (T) is since it's not in the template angle braces.

Share this post


Link to post
Share on other sites
Juliean    7068

Wait.. since when do you need a different sqrt-function for different data types? Did I miss somehing, or is this just an example? You could however delegate this problem with using a global function that is overloaded for the different data types:

void mySqrt(int x)
{
return sqrtl(x);
}

void mySqrt(float x)
{
return sqrt(x);
}

void mySqrt(double x)
{
return sqrt(x);
}

Now call mySqrt in length() instead of sqrt, and only provide this one implementation, the correct function overload will be choosen for you. Downside is that you now need an explicit implementation for every data type, unless this works with a forth templated function too (you'd have to try).

 

EDIT: Being ninja'd by the OP... now that just sucks :P

Edited by Juliean

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this