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?
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
Technical overview. There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.
Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.
Assuming it's actually necessary to use different values in the two specializations (it's not necessary for 0.5 and 0.5f, for example) it would be a lot less typing to do:
template <typename T>
class SomeClass
{
public:
T doSomething(T x);
private:
static const T magic_number_1;
};
template <typename T>
T SomeClass<T>::doSomething(T x)
{
T y = magic_number_1;
/*
* Do computations...
*/
return x;
}
template <>
const float SomeClass<float>::magic_number_1 = 0.5f;
template <>
const double SomeClass<double>::magic_number_1 = 0.5;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With