Created
December 26, 2016 12:33
-
-
Save illescasDaniel/1caaf60247c1b5b5ecca4c5b2db28dac to your computer and use it in GitHub Desktop.
Guard statement (from Swift) in C++
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
| #include <iostream> | |
| using namespace std; | |
| // Guard function | |
| template <typename Condition, typename Function> | |
| bool guard(const Condition& condition, Function function) { | |
| if (bool(!condition)) { | |
| function(); | |
| return true; | |
| } | |
| return false; | |
| } | |
| // Example using the return value | |
| template <typename Type> | |
| Type biggestNumber(Type* numbers, const size_t& size) { | |
| if (guard(numbers != nullptr, [](){ cerr << "[Error: null pointer found] "; })) { return Type{}; } | |
| Type biggest = 0; | |
| for (size_t i = 0; i < size; ++i) { | |
| if (numbers[i] > biggest) { | |
| biggest = numbers[i]; | |
| } | |
| } | |
| return biggest; | |
| } | |
| int main() { | |
| boolalpha(cout); | |
| int* i = new int{10}; // nullptr; | |
| guard(i != nullptr, [](){ cerr << "Null pointer" << endl; exit(1); }); | |
| guard(*i == 11, [](){ cerr << "Incorrect value" << endl; }); | |
| delete i; | |
| // | |
| double* numbers = nullptr; //new double[4]{1.1, 2.3, 9.01, 9.0}; | |
| cout << "Biggest number: " << biggestNumber(numbers, 4) << endl; | |
| delete[] numbers; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment