Created
November 7, 2017 16:32
-
-
Save DrFrankenstein/c562b114eee44131e1064022af91c8a7 to your computer and use it in GitHub Desktop.
Exception-based isEven in C++. >;D
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 <limits> | |
#include <exception> | |
class OverflowException : public std::exception | |
{ | |
}; | |
struct SafeInt | |
{ | |
int n; | |
SafeInt(int n) : n(n) { } | |
operator int() { return n; } | |
int operator +(int addend) | |
{ | |
if (std::numeric_limits<int>::max() - addend > n) | |
throw OverflowException(); | |
return n + addend; | |
} | |
}; | |
bool isEven(SafeInt n) | |
{ | |
try | |
{ | |
if (n == std::numeric_limits<int>::max()) | |
return false; | |
else | |
return isEven(n + 2); | |
} | |
catch (OverflowException ox) | |
{ | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment