Created
September 8, 2014 17:58
-
-
Save agrippa1994/e75a5754b87f589b186c to your computer and use it in GitHub Desktop.
c++1y safe call
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 <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