What is the best practice for casting between the different number types? Types float, double, int are the ones I use the most in C++.
An example of the options where f is a float and n is a double or an int:
float f = static_cast<float>(n);
float f = float(n);
float f = (float)n;
I usually write static_cast<T>(...) but wondered if there was any consensus within the C++ development community if there is a preferred way.
I appreciate this is may end up being an opinion based question and there may not be a "standard" way, in which case please let me know that there is no standard way so at least I know that :-)
I know this question has cropped up in relation to casting in general, however, I am interested specifically in numbers and whether there are specific best practices in the approach for number types.
Just use
static_cast. The problem with C casts is the ambiguity of the operation (i.e. point (1) of Explicit type conversion).C++ casts avoid this. Additionally C++ casts are more visible when searching for them.
Using Stroustrup's words (What good is static_cast?):
Also consider
boost::numeric::converter/boost::numeric_castthat are safer alternatives (part of Boost.NumericConversion library).E.g.
In general for both implicit conversions and explicit conversions (through
static_cast) the lack of preservation of range makes conversions between numeric types error prone.numeric_castdetects loss of range when a numeric type is converted and throws an exception if the range cannot be preserved.