Class methods return type template specialization
Please look at the following example:
#include <Math.h>
template <typename T>
class MySqrt
{
public:
float Sqrt()
{
return sqrt(static_cast<float>(3.141592));
}
};As you might know:
sqrt(..) returns float if given float
sqrt(..) returns double if given double
sqrt(..) returns long double if given long double
How do i templatize (or specialize) my method (Sqrt()) so that it returns
float for all types,
double for T == double and
long double for T == long double.
Thank you
Kresimir
[600 byte] By [
l00p1n6] at [2007-11-20 6:27:28]

# 1 Re: Class methods return type template specialization
Hi.
If you want to present a different behaviour for double types, one option is specialize your class like this:
template <typename T>
class MySqrt
{
//...
};
template <>
class MySqrt<double>
{
//...
};
You can then write the sqrt function in the way you want for each class.
# 2 Re: Class methods return type template specialization
Thank you!
But what if i have many other methods besides Sqrt() in class MySqrt, and want only Sqrt() to be specialized?
Surely you wouldn't suggest copy/paste and rewriting only Sqrt(), would you?
# 3 Re: Class methods return type template specialization
Hi.
One option is to use composition. You could create a class with the all basic operations and delegate calls to MySqrt to this class (which could a member of MySqrt). Another option is to inherit MySqrt from a class that provides the functions you need. There're probably other options, these are just two that came into my mind at this moment.
# 4 Re: Class methods return type template specialization
That is alas what you need to do. Of course if there is anthing more than one simple statement in the specialization then I would factor it out to a common (non-public) method to avoid duplication of the logic.
# 5 Re: Class methods return type template specialization
Thank you.
I was afraid you would say something like that :(
Although i have thought of inheritance, composition is, on the other hand, a new idea. Maybe I'll try it sometime.
Doesn't C++ provide some simpler templating of the return type?
Something like:
//THIS IS NOT A VALID CODE
// for the default type
float Sqrt<>()
{
return sqrt(static_cast<float>(3.141592));
}
// for the default type
float Sqrt<T>()
{
return sqrt(static_cast<float>(3.141592));
}
// for the double
double Sqrt<double>()
{
return sqrt(static_cast<double>(3.141592));
}
// for the long double
long double Sqrt<long double>()
{
return sqrt(static_cast<long double>(3.141592));
}
//THIS IS NOT A VALID CODE
Right now I'm using something like this, and it works
template <typename T, typename U = float>
class MySqrt
{
public:
U Sqrt()
{
return sqrt(static_cast<U>(3.141592));
}
};
With "U" parameter one can set the sqrt(..) precision, but that's not the solution because, as you might know, someone could use int or something else for "U".
Btw: "T" is used elsewhere in the class, this is just a simplified case.