forked from jeaye/color_coded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafe_func.hpp
50 lines (44 loc) · 1.15 KB
/
safe_func.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#pragma once
#include <string>
#include <utility>
#include <stdexcept>
#include "core.hpp"
namespace color_coded
{
namespace detail
{
template <typename T, T F>
struct safe_func;
template <typename R, typename... Args, R (*F)(Args...)>
struct safe_func<R (*)(Args...), F>
{
/* XXX: Function pointers and forwarding refs don't
* play nicely together. Copy in and move out. */
template <typename... Args_>
static R call(Args_... args)
try
{ return F(std::move(args)...); }
catch(std::exception const &e)
{
core::last_error(std::string{"exception: "} + e.what());
return {};
}
catch(...)
{
core::last_error("unknown error");
return {};
}
};
template <typename T, T F>
struct make_safe_func;
template <typename R, typename... Args, R (*F)(Args...)>
struct make_safe_func<R (*)(Args...), F>
{
static R constexpr (*value)(Args...)
{ &safe_func<R (*)(Args...), F>::template call<Args...> };
};
}
template <typename F, F f>
auto constexpr safe_func()
{ return detail::make_safe_func<F, f>::value; }
}