Thank you all for your answers and comments. I allowed myself to make a summary of what has been said so far and add my conclusions.
I am going to implement some math class template that will be created for use with float or double. Some numeric literals must be used inside the class. These will be commonly used numeric literals and constants, such as 0.0, 0.5, 1.0, pi, etc. I am looking for a solution to create an instance of a class for different literals depending on its type.
Should float and double be used literals or not?
The discussion is a bit on the topic of whether to use separate literals for float and double. This may be caused by a slightly unfortunate example that I gave in my question. In the example, the literal will in any case be converted to the correct type, so there will be no harm. But in general there will be cases when a literal should be used in an expression, for example:
float foo(float x) { return x * 3.14; }
This will force the compiler to convert x to double, perform the calculations, and then convert the result back to float. Pros and cons of this behavior:
Pros:
- Exact gain, because the actual calculations will be performed in double precision.
Minuses:
- If performance is a problem, it can lead to faster as well as slower execution, depending on the environment and platform. This introduces some performance changes depending on the implementation, which as far as I think is bad.
- Introduces inconsistency in the calculations, since some operations will be done on floats, and some on paired ones, depending on the use of literals. This may also open some errors.
- This violates the idea of class specialization for floats in the first place because internal calculations will be performed by doubling anyway.
In conclusion, the goal is to instantiate the class for the correct types without any additional conversions. The idea of using double type literals around the world, such as 0.5 and leaving the proper conversion processing to the compiler, is not an option.
Related topics: Should we usually use float literals for float instead of simpler double literals?
Possible solutions?
- Specialize methods for each type of template instance where literals should be used. This is probably the worst solution because it forces you to write the same code twice with minor changes to literals.
- Make specialized methods
getValue<type>() or as Jonathan Wackel published - specialized members. This can lead to some stupid members or methods in the class, such as getZeroPointFive<float>() . - Mohammad and Tony Delroy noted that wrapping each literal with
static_cast<T>() would do the trick. Converting to the correct type will be at compile time.
umebe
source share