c++ - Extracting function argument types as a parameter pack -
this followup question "unpacking" tuple call matching function pointer, asked how provide values std::tuple
arguments function in generic way. solution given there following:
template<int ...> struct seq { }; template<int n, int ...s> struct gens : gens<n-1, n-1, s...> { }; template<int ...s> struct gens<0, s...> { typedef seq<s...> type; }; double foo(int x, float y, double z) { return x + y + z; } template <typename... args> struct save_it_for_later { std::tuple<args...> params; double (*func)(args...); double delayed_dispatch() { return callfunc(typename gens<sizeof...(args)>::type()); } template<int ...s> double callfunc(seq<s...>) { return func(std::get<s>(params) ...); } }; int main(void) { std::tuple<int, float, double> t = std::make_tuple(1, 1.2, 5); save_it_for_later<int,float, double> saved = {t, foo}; std::cout << saved.delayed_dispatch() << std::endl; }
my question whether there's way make alternate version of save_it_for_later
takes foo
template argument, don't have provide foo
's parameter types template argument (or bake return type save_it_for_later
). like
int main(void) { ... save_it_for_later2<foo> saved = {t}; ... }
i'd equally fine sort of macro wrapping foo
extract required types:
int main(void) { ... save_it_for_later<macro_using_decltype_or_somesuch(foo)> saved = {t}; ... }
this concern seems orthogonal enough original question warrant own ticket.
#include <tuple> #include <utility> template <typename> struct save_it_for_later_t; template <typename result, typename... args> struct save_it_for_later_t<result (*)(args...)> { std::tuple<args...> params; result (*fun)(args...); template <typename... params> save_it_for_later_t(result (*fun)(args...), params&&... params) : params(std::forward<params>(params)...) , fun(fun) { } // ... }; template <typename result, typename... args, typename... params> save_it_for_later_t<result(*)(args...)> save_it_for_later(result (*fun)(args...), params&&... params) { return save_it_for_later_t<result(*)(args...)>(fun, std::forward<params>(params)...); } double foo(float, float, double); int main() { auto saved = save_it_for_later(foo, 1.2f, 3.4f, 5.6); // ... }
Comments
Post a Comment