Skip to content

Instantly share code, notes, and snippets.

@gnaggnoyil
Last active December 20, 2016 13:36
Show Gist options
  • Save gnaggnoyil/86b497da22372b28bb7b3e9434adf51c to your computer and use it in GitHub Desktop.
Save gnaggnoyil/86b497da22372b28bb7b3e9434adf51c to your computer and use it in GitHub Desktop.
literal compare
namespace _detail{
template <typename Signed1, typename Signed2>
inline constexpr short compareImpl(Signed1 x, Signed2 y, std::true_type, std::true_type){
return (x < y)? -1: ((x > y)? 1: 0);
}
template <typename Unsigned1, typename Unsigned2>
inline constexpr short compareImpl(Unsigned1 x, Unsigned2 y, std::false_type, std::false_type){
return (x < y)? -1: ((x > y)? 1: 0);
}
template <typename Signed, typename Unsigned>
inline constexpr short compareImpl(Signed x, Unsigned y, std::true_type, std::false_type){
// just need common is a type equal to or bigger than greater(signed_t<Signed>, Unsigned)
using common = typename std::common_type<Signed, Unsigned>::type;
return (x < 0)? -1:
compareImpl(static_cast<common>(x), static_cast<common>(y),
std::is_signed<common>{}, std::is_signed<common>{});
}
template <typename Unsigned, typename Signed>
inline constexpr short compareImpl(Unsigned x, Signed y, std::false_type, std::true_type){
using common = typename std::common_type<Unsigned, Signed>::type;
return (y < 0)? 1:
compareImpl(static_cast<common>(x), static_cast<common>(y),
std::is_signed<common>{}, std::is_signed<common>{});
}
} // namespace _detail
template <typename Int1, typename Int2>
inline constexpr short compareInt(Int1 x, Int2 y){
return _detail::compareImpl(x, y, std::is_signed<Int1>{}, std::is_signed<Int2>{});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment