Using std::apply in a class template

1 day ago 2
ARTICLE AD BOX

First, without a MRE, it is difficult to answer the specific reason for the compilation error.

Actually, since you have a std::function and a std::tuple, you can directly call std::apply as follows

std::apply(function, function_args);

because std::apply essentially invokes a callable (such as a std::function object) with arguments being the tuple elements. Technically, these elements are retrieved with std::get<I>(function_args) with I coming from a std::index_sequence.

For the constructor, a parameter pack has to be put in last position in a function parameters list, so you should have instead:

ViewPath(std::function<void(Types...)> function, Types...args) : function_args(args...), function(function) {}

Now, the fun part concerns what you can provide to the constructor. Suppose we have the following function:

auto foo (int n, const char* s);

then you could write this:

ViewPath(std::function{foo},1,"bar").executeFunction();

but not that one that would lead to a compile error

ViewPath(foo,1,"bar").executeFunction();

It could however be fixed by adding a user deduction guide as mentionned here

template<typename Callable, typename... Args> ViewPath(Callable, Args...) -> ViewPath<Args...>;

Depending on your use case, you might also not use std::function and instead directly use a function pointer.

template<class... Types> class ViewPath { public: ViewPath(void(*fct)(Types...), Types...args) : function(fct), function_args(args...) {} void executeFunction() const { std::apply(function, function_args); } private: void(*function)(Types...); std::tuple<Types...> function_args; }; auto foo (int n, const char* s) { std::println ("{} {}", n,s); } int main() { ViewPath(foo,1,"bar").executeFunction(); }

Demo

Read Entire Article