I have a class memoize
which deducts the variadic argument list of a function pointer passed to it as a template parameter (see code below).
I would like to be able to do the same thing for a lambda, but I don't seem to find the right way to do it. Ideally it should work when uncommenting and completing the last line of the main() function below (or see on https://godbolt.org/z/Y8G47h4GK).
#include <tuple>
#include <iostream>
template<typename... Ts> struct pack { };
template <class> struct pack_helper;
template <class R, class... Args>
struct pack_helper<R(Args...)> {
using args = pack<Args...>;
};
template <class R, class... Args>
struct pack_helper<R(*)(Args...)> {
using args = pack<Args...>;
};
template <class F, class = typename pack_helper<F>::args>
class memoize;
template <class F, class... Args>
class memoize<F, pack<Args...>>
{
public:
using result_type = std::invoke_result_t<F, Args...>;
memoize(F &&f) : _f(std::forward<F>(f)) {}
result_type operator()(Args... args) { return _f(args...); }
private:
F _f;
};
int test(int x) { return x + 1; }
int main() {
auto test_mem = memoize<decltype(&test)>(&test);
std::cout << test_mem(2) << '\n';
auto l = [](int x) -> int { return x + 1; };
// auto l_mem = memoize<?>(?);
}