packio
as.h
Go to the documentation of this file.
1 #ifndef PACKIO_AS_H
2 #define PACKIO_AS_H
3 
6 
7 #include <type_traits>
8 #include <utility>
9 #include <msgpack.hpp>
10 
11 #include "error_code.h"
12 #include "internal/config.h"
13 #include "internal/utils.h"
14 #include "traits.h"
15 
16 namespace packio {
17 
28 template <typename Result, typename AsCallHandler>
29 auto as(
30  AsCallHandler&& handler,
31  std::enable_if_t<!std::is_void_v<Result>, void*> = nullptr)
32 {
33  PACKIO_STATIC_ASSERT_TTRAIT(AsCallHandler, Result);
34  return [handler = std::forward<AsCallHandler>(handler)](
35  error_code ec, msgpack::object_handle result) mutable {
36  if (ec) {
37  handler(ec, std::nullopt);
38  }
39  else {
40  try {
41  handler(ec, std::optional<Result>{result->as<Result>()});
42  }
43  catch (msgpack::type_error&) {
44  ec = make_error_code(error::bad_result_type);
45  handler(ec, std::nullopt);
46  }
47  }
48  };
49 }
50 
57 template <typename Result, typename AsVoidCallHandler>
58 auto as(
59  AsVoidCallHandler&& handler,
60  std::enable_if_t<std::is_void_v<Result>, void*> = nullptr)
61 {
62  PACKIO_STATIC_ASSERT_TRAIT(AsVoidCallHandler);
63  return [handler = std::forward<AsVoidCallHandler>(handler)](
64  error_code ec, msgpack::object_handle result) mutable {
65  if (!ec && result->type != msgpack::type::NIL) {
66  ec = make_error_code(error::bad_result_type);
67  }
68  handler(ec);
69  };
70 }
71 
72 } // packio
73 
74 #endif // PACKIO_AS_H
packio::as
auto as(AsCallHandler &&handler, std::enable_if_t<!std::is_void_v< Result >, void * >=nullptr)
Function used to wrap a typed call handler.
Definition: as.h:29
packio::error::bad_result_type
@ bad_result_type
The result type is not as expected.
error_code.h
packio
Definition: as.h:16
traits.h