Skip to content

Instantly share code, notes, and snippets.

@agrippa1994
Created September 8, 2014 17:58
Show Gist options
  • Save agrippa1994/e75a5754b87f589b186c to your computer and use it in GitHub Desktop.
Save agrippa1994/e75a5754b87f589b186c to your computer and use it in GitHub Desktop.
c++1y safe call
#include <iostream>
#include <string>
#include <type_traits>
#include <experimental/optional>
template<
typename pred, typename ...args,
typename ret = std::experimental::optional<typename std::result_of<pred(args...)>::type>
>
ret safe_call(pred f, args&& ...params)
{
try {
return ret(f(params...));
} catch(...) {
return ret();
}
}
auto incrementIfNotZero(int x)
{
if(x == 0)
throw std::string("Error, x is zero!");
return ++x;
}
int main(int argc, const char * argv[])
{
for(auto i : {-1, 0, 1, 2})
if(auto ret = safe_call(incrementIfNotZero, i))
std::cout << "Die Zahl wurde inkrementiert: " << *ret << std::endl;
else
std::cout << "Die Zahl konnte nicht inkrementiert werden!" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment