saturate_cast
- Dominant language
- C++
- Stars
- 156
- Forks
- 116
- PR merge metrics
- No merged PRs in 30d
Description
With C++26, there is std::saturate_cast https://en.cppreference.com/w/cpp/numeric/saturate_cast.html
Can you provide this as well?
I'm not sure if boost::core is the right library.
My implementation requires boost::is_integer (https://github.com/boostorg/type_traits/issues/186), but they didn't understand what I meant and therefore rejected/closed it.
```
// Distributed under the Boost Software License Version 1.0 https://www.boost.org/LICENSE_1_0.txt
// Copyright Gero Peterhoff
#ifndef BOOST_CORE_SATURATE_CAST_HPP
#define BOOST_CORE_SATURATE_CAST_HPP
#include
#include
namespace boost
{
namespace core
{
template
inline BOOST_CXX14_CONSTEXPR typename std::enable_if::value && boost::is_integer::value, To>::type saturate_cast(const From& from) noexcept
{
using limits = std::numeric_limits;
BOOST_IF_CONSTEXPR (std::is_same::value)
{
return from;
}
else BOOST_IF_CONSTEXPR (std::is_signed::value && std::is_unsigned::value)
{
using type = typename std::make_unsigned::type;
return
(from > type(limits::max())) ? limits::max() :
To(from);
}
else BOOST_IF_CONSTEXPR (std::is_unsigned::value && std::is_signed::value)
{
using type = typename std::make_unsigned::type;
return
(from < 0) ? To{} :
(type(from) > limits::max()) ? limits::max() :
To(from);
}
else BOOST_IF_CONSTEXPR (std::is_signed::value && std::is_signed::value)
{
return
(from < limits::min()) ? limits::min() :
(from > limits::max()) ? limits::max() :
To(from);
}
else
{
return
(from > limits::max()) ? limits::max() :
To(from);
}
}
} // core
} // boost
#endif // BOOST_CORE_SATURATE_CAST_HPP
```
thx
Gero
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.