Last active
October 18, 2016 14:17
-
-
Save withzombies/0b0bbec5aba6642d81ad4a41e34deb48 to your computer and use it in GitHub Desktop.
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 <experimental/optional> | |
#define LIFT(fname) \ | |
[] (auto&&... args) -> decltype (auto) \ | |
{ \ | |
return fname (std::forward <decltype (args)> (args)...); \ | |
} | |
template<typename Func, typename... Args> | |
auto try_call(Func f, Args&&... args) noexcept -> std::experimental::optional<std::decay_t<decltype(f(std::forward<Args>(args)...))>> | |
{ | |
using RT = std::decay_t<decltype(f(std::forward<Args>(args)...))>; | |
try { | |
return std::experimental::make_optional<RT>(f(std::forward<Args>(args)...)); | |
} catch(...) { | |
return std::experimental::nullopt; | |
} | |
} | |
int func1(char * ptr) | |
{ | |
if (!ptr) | |
throw 14; | |
return strlen(ptr); | |
} | |
int func1(char * ptr, size_t len) | |
{ | |
if (!ptr) | |
throw 14; | |
const size_t calc_len = strlen(ptr); | |
return calc_len < len ? calc_len : len; | |
} | |
int main(int argc, char **argv) | |
{ | |
char *omg = "omg"; | |
// This syntax isn't ideal | |
auto val = try_call(LIFT(func1), omg); | |
if (val) | |
std::cout << omg << " has a length of " << *val << "\n"; | |
else | |
std::cout << "Something went wrong...\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment