How to prevent such code from compiling?
#include
#include
#include
#include
int main() {
std::
I solve this by templates and specialisation:
template<
typename T/*the desired type*/,
typename Y/*the source type*/
> T integral_cast(const Y& y)
{
static_assert(false, "undefined integral_cast");
}
which I then specialise at leisure if I want the cast to work:
// Pass through for uint32_t
template<>
inline std::uint32_t integral_cast(const uint32_t& y)
{
return y;
}
and
// Specialisation to convert std::uint32_t to double
template<>
inline double integral_cast(const std::uint32_t& y)
{
double ret = static_cast(y); // this never loses precision under IEEE754
return ret;
}
At the point of use you write code of the form
int16_t y = integral_cast(std::numeric_limits::max());