How to specialize template for method

Started by
2 comments, last by smr 10 years, 10 months ago

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++

Advertisement

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.

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

Good point. I forgot that sqrt is overloaded anyway. Thanks!

This topic is closed to new replies.

Advertisement