I want to save a generic callable with its state for later use. Please see the example code bellow. I could probably use std::function
or std::bind
to achieve this but I do not know what is best. Also please note that in the main()
of the example below, the capturedInt
must be saved in the state of the callable.
What are the possibilities for:
makeCallable(fun, args...) { ... }
CallableType
template <typename RetT> class Service { public: template <typename Fn, typename... Args> Service(Fn&& fun, Args&&... args) { m_callable = makeCallable(fun, args...); } Run() { m_callable(); } CallableType<RetT> m_callable; }; // Template deduction guides (C++17) template <typename Fn, typename... Args> Service(Fn&& fun, Args&&... args) -> Service<std::invoke_result_t<std::decay_t<Fn>, std::decay_t<Args>...>>; int main() { Service* s = nullptr; { int capturedInt = 5; s = new Service([capturedInt]() { std::cout << capturedInt << std::endl; } ); } s->Run(); }