Peano
Loading...
Searching...
No Matches
lambda.h
Go to the documentation of this file.
1#pragma once
2
3#include <tuple>
4
5template<typename Functor, typename ...Args>
6class Lambda {
7 Functor f;
8 std::tuple<Args...> state;
9
10 template<std::size_t I>
11 constexpr auto &getArg(auto &&invocationArgs) {
12 constexpr auto STATE_ARGS_SIZE = std::tuple_size_v<decltype(this->state)>;
13
14 if constexpr (I < STATE_ARGS_SIZE) return std::get<I>(this->state);
15 else return std::get<I - STATE_ARGS_SIZE>(invocationArgs);
16 }
17
18 template<std::size_t ...I>
19 constexpr auto invoke(auto &&invocationArgs, std::index_sequence<I...>) -> decltype(this->f(this->getArg<I>(invocationArgs)...)) {
20 return this->f(this->getArg<I>(invocationArgs)...);
21 }
22
23public:
24 constexpr Lambda() = default;
25
26 constexpr explicit Lambda(Functor f, Args ...args) : f(f), state(std::forward_as_tuple(args...)) {}
27
28 // The auto return type affects how concepts are checked
29 // i.e. when the variable doesn't meet the requirements of a concept,
30 // a hard compile error is emitted.
31 //
32 // The '-> decltype' syntax gives the compiler the hand it needs
33 // to deduce the return type without throwing a compile error.
34 // https://stackoverflow.com/questions/64186621/why-doesnt-stdis-invocable-work-with-templated-operator-which-return-type-i
35 template<typename ...InvArgs>
36 constexpr auto operator()(InvArgs &&...invArgs) -> decltype(this->invoke(std::forward_as_tuple(invArgs...), std::make_index_sequence<std::tuple_size_v<decltype(this->state)> + std::tuple_size_v<decltype(std::forward_as_tuple(invArgs...))>>{})) {
37 auto invocationArgs = std::forward_as_tuple(invArgs...);
38
39 constexpr auto STATE_ARGS_SIZE = std::tuple_size_v<decltype(this->state)>;
40 constexpr auto INVOCATION_ARGS_SIZE = std::tuple_size_v<decltype(invocationArgs)>;
41
42 return this->invoke(invocationArgs, std::make_index_sequence<STATE_ARGS_SIZE + INVOCATION_ARGS_SIZE>{});
43 }
44};
Definition lambda.h:6
constexpr Lambda()=default
std::tuple< Args... > state
Definition lambda.h:8
constexpr auto invoke(auto &&invocationArgs, std::index_sequence< I... >) -> decltype(this->f(this->getArg< I >(invocationArgs)...))
Definition lambda.h:19
constexpr Lambda(Functor f, Args ...args)
Definition lambda.h:26
constexpr auto operator()(InvArgs &&...invArgs) -> decltype(this->invoke(std::forward_as_tuple(invArgs...), std::make_index_sequence< std::tuple_size_v< decltype(this->state)>+std::tuple_size_v< decltype(std::forward_as_tuple(invArgs...))> >{}))
Definition lambda.h:36
Functor f
Definition lambda.h:7
constexpr auto & getArg(auto &&invocationArgs)
Definition lambda.h:11
STL namespace.