Created
October 16, 2015 21:59
-
-
Save goldsborough/7743e9e8aacf6549a9b0 to your computer and use it in GitHub Desktop.
Determine the greater of two values without using comparison operators.
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
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