I'm trying to find a solution to have constant numeric literals inside template class method. I'm making some math template classes to be used with float or double types. The problem is that literals are different depending on data type (for example "0.5f" for float and "0.5" for double). So far, I come up with two solutions. Some hypothetical code for first one:
template <typename T>
class SomeClass
{
public:
T doSomething(T x);
};
template <>
float SomeClass<float>::doSomething(float x)
{
float y = 0.5f;
/*
* Do computations...
*/
return x;
}
template <>
double SomeClass<double>::doSomething(double x)
{
double y = 0.5;
/*
* Do computations...
*/
return x;
}
The approach above forces rewriting whole methods for every type it is used with.
Another approach:
template <typename T>
class SomeClass
{
public:
T doSomething(T x);
private:
T getValue();
};
template <typename T>
T SomeClass<T>::doSomething(T x)
{
T y = getValue();
/*
* Do computations...
*/
return x;
}
template <>
float SomeClass<float>::getValue()
{
return 0.5f;
}
template <>
double SomeClass<double>::getValue()
{
return 0.5;
}
This one doesn't require to write same methods multiple times for specific type, but requires to have a lot getValue() methods for every "magic number" that need to be used inside the method.
Is there another, "more elegant" way to solve this?