Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created October 16, 2015 21:59
Show Gist options
  • Save goldsborough/7743e9e8aacf6549a9b0 to your computer and use it in GitHub Desktop.
Save goldsborough/7743e9e8aacf6549a9b0 to your computer and use it in GitHub Desktop.
Determine the greater of two values without using comparison operators.
template<typename T>
constexpr bool is_positive(const T& value)
{
return ! (value & 1 << (sizeof(T) * 8 - 1));
}
template<bool condition>
struct determine;
template<>
struct determine<true>
{
template<typename T>
const T& operator()(const T& first, const T& second) const
{
return first;
}
};
template<>
struct determine<false>
{
template<typename T>
const T& operator()(const T& first, const T& second) const
{
return second;
}
};
int main(int argc, char* argv[])
{
constexpr int first = -4;
constexpr int second = -5;
constexpr int result = first - second;
auto max = determine<is_positive(result)>()(first, second);
print::ln(max);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment