Skip to content

Instantly share code, notes, and snippets.

@withzombies
Last active October 18, 2016 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save withzombies/0b0bbec5aba6642d81ad4a41e34deb48 to your computer and use it in GitHub Desktop.
Save withzombies/0b0bbec5aba6642d81ad4a41e34deb48 to your computer and use it in GitHub Desktop.
#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