Similar to C++ int_cast<> function for checked casts?, but C++20, and with target type deduced from context.
The goal is to implement a runtime check that the value being converted can be represented in the target type, and throw an exception if it can't.
This basically works for my use case, but I wonder if there's anything obvious I've missed.
Use as
std::uint32_t x = 0x40000000;
std::int32_t y = checked_cast(x); // works
std::uint16_t z = checked_cast(x); // throws
Code:
#pragma once
#include <stdexcept>
#include <utility>
class bad_checked_cast : public std::logic_error
{
public:
bad_checked_cast() : std::logic_error("Bad checked_cast") { }
};
template<typename From>
struct checked_cast_result_proxy
{
template<typename To>
operator To() const
{
if(std::in_range<To>(value))
return static_cast<To>(value);
else
throw bad_checked_cast();
}
From value;
};
template<typename From>
auto checked_cast(From value) -> checked_cast_result_proxy<From>
{
return checked_cast_result_proxy<From> { value };
}