Created
September 17, 2013 18:51
-
-
Save PureAbstract/6598949 to your computer and use it in GitHub Desktop.
parse unsigned UDL
This file contains 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
#include <type_traits> | |
#include <limits> | |
#include <cstdint> | |
namespace detail { | |
template<std::uintmax_t Value> | |
constexpr std::uintmax_t parse_unsigned_literal() | |
{ | |
return Value; | |
} | |
template<char C> | |
constexpr std::uintmax_t parse_char_unsigned() | |
{ | |
return C - '0'; | |
} | |
template<std::uintmax_t Value, char C0, char ...Rest> | |
constexpr std::uintmax_t parse_unsigned_literal() | |
{ | |
return parse_unsigned_literal<(Value*10u) + parse_char_unsigned<C0>(),Rest...>(); | |
} | |
template<typename T, char ...Chars> | |
constexpr T checked_unsigned_literal() | |
{ | |
static_assert( detail::parse_unsigned_literal<0ull,Chars...>() <= std::numeric_limits<T>::max(), | |
"check_unsigned_literal : out of range" ); | |
return static_cast<T>( detail::parse_unsigned_literal<0ull,Chars...>() ); | |
} | |
} | |
template<char ...cs> | |
constexpr unsigned short operator"" _us() | |
{ | |
return detail::checked_unsigned_literal<unsigned short, cs...>(); | |
} | |
template<char ...cs> | |
constexpr unsigned long operator"" _ul() | |
{ | |
return detail::checked_unsigned_literal<unsigned long, cs...>(); | |
} | |
constexpr auto x = 1234_us; | |
static_assert( std::is_same<const unsigned short,decltype(x)>::value, "x - type" ); | |
static_assert( x == (unsigned short)(1234), "x - value" ); | |
constexpr auto y = 0_us; | |
static_assert( std::is_same<const unsigned short,decltype(y)>::value, "y - type" ); | |
static_assert( y == (unsigned short)(0), "y - value" ); | |
constexpr auto z = 65535_us; | |
static_assert( std::is_same<const unsigned short,decltype(z)>::value, "z - type" ); | |
static_assert( z == (unsigned short)(65535), "z - value" ); | |
constexpr auto l = 12345678890_ul; | |
static_assert( std::is_same<const unsigned long,decltype(l)>::value, "l - type" ); | |
static_assert( l == 12345678890ul, "l - value" ); | |
// constexpr auto f = 65536_us; // fails | |
int main() | |
{ | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment