Function round_to is not standard and I don't know how it is actually implemented.
In our code base, we use floor_cast, ceil_cast and round_cast that probably are very similar to the mentioned round_to.
To convert floating point numbers to integers, we should use a template function like those. Compared to raw static_cast<int>(std::round(f)), round_cast<int>(f) has the following advantages:
- Much faster, standard
round is typically rather slow
- No undefined behavior due to integer overflow
- Cleaner
- Easier to search in code base
// Adapted from: https://stackoverflow.com/a/30308919
#include <concepts>
template<std::integral I, std::floating_point F> [[nodiscard]] I floor_cast(F value)
{
int64_t w = static_cast<int64_t>(value);
return static_cast<I>(w - (value < w));
}
template<std::integral I, std::floating_point F> [[nodiscard]] I ceil_cast(F value)
{
int64_t w = static_cast<int64_t>(value);
return static_cast<I>(w + (value > w));
}
template<std::integral I, std::floating_point F> [[nodiscard]] I round_cast(F value)
{
return floor_cast<I>(value + 0.5);
}
round_towas never a standard function and it seems it's not inPPP_support.h(anymore at least). You could usestd::round(y);from<cmath>instead. You may get a warning so you could do an explicit cast:int x = static_cast<int>(std::round(y));. You could also define your ownround_toliketemplate<class To, class From>To round_to(From y) { return static_cast<To>(std::round(y)); }