Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template function that takes float or double

Tags:

c++

c++11

I want to write a template function that will work on both double and float, something like that:

template <typename T>
constexpr auto someCalc(const T x) {
    return x * 4.0 + 3.0;
}

My issue is that both 4.0 and  3.0 are doubles literal, thus I get the following error on clang:

error: implicit conversion increases floating-point precision: 'const float' to 'double' [-Werror,-Wdouble-promotion]

Is there an elegant way to write this code without having the up-conversion to double? The best I can come up with, is this

template <typename T>
constexpr auto someCalc(const T x) {
    constexpr T four = 4.0;
    constexpr T three = 3.0;
    return x * four + three;
}

which I find less readable and harder to maintain for larger/more complicated function.

like image 359
Jonathan Drolet Avatar asked Nov 22 '25 03:11

Jonathan Drolet


1 Answers

I would do it this way:

template <typename T>
constexpr auto someCalc(const T x) {
    return x * T(4.0) + T(3.0);
}

Or with static_cast, if you prefer it.

like image 194
HolyBlackCat Avatar answered Nov 24 '25 19:11

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!