Created
June 10, 2016 05:59
-
-
Save gocha/553206e73ead17f0f52dd101cdba65f8 to your computer and use it in GitHub Desktop.
Numeric cast with a simple range check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// @file | |
/// Numeric cast with a simple range check. | |
#ifndef NUMERIC_CAST_HPP_ | |
#define NUMERIC_CAST_HPP_ | |
#include <limits> | |
/// Cast a numeric value with a simple range check. | |
/// @param arg the numeric value to cast. | |
/// @tparam Target the target type. | |
/// @tparam Source the source type. | |
/// @return the numeric value in Target type. | |
/// @throws std::out_of_range if the number is out of range of std::numeric_limits<Target>. | |
template <typename Target, typename Source> | |
inline Target numeric_cast(Source arg) { | |
if (arg < static_cast<Source>(std::numeric_limits<Target>::lowest())) { | |
throw std::out_of_range("numeric_cast out of range"); | |
} | |
if (arg > static_cast<Source>(std::numeric_limits<Target>::max())) { | |
throw std::out_of_range("numeric_cast out of range"); | |
} | |
return static_cast<Target>(arg); | |
} | |
#endif // !NUMERIC_CAST_HPP_ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment