Skip to content

Instantly share code, notes, and snippets.

@illescasDaniel
Created December 26, 2016 12:33
Show Gist options
  • Select an option

  • Save illescasDaniel/1caaf60247c1b5b5ecca4c5b2db28dac to your computer and use it in GitHub Desktop.

Select an option

Save illescasDaniel/1caaf60247c1b5b5ecca4c5b2db28dac to your computer and use it in GitHub Desktop.
Guard statement (from Swift) in C++
#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