提取函数参数类型作为参数包 [英] Extracting function argument types as a parameter pack

查看:41
本文介绍了提取函数参数类型作为参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对>拆包"的后续问题.一个元组以调用匹配的函数指针,该元组询问如何以通用方式将 std :: tuple 中的值提供为函数的参数.给出的解决方案如下:

This is a followup question to "unpacking" a tuple to call a matching function pointer, which asked how to provide the values from a std::tuple as arguments to a function in a generic way. A solution given there was the 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;
}

我的问题是是否有办法制作仅使用 foo 作为模板参数的 save_it_for_later 的替代版本,因此我们不必提供 foo 的参数类型作为模板参数(或将其返回类型烘烤为 save_it_for_later ).像

My question is whether there's way to make an alternate version of save_it_for_later which takes only foo as a template argument, so that we don't have to provide foo 's parameter types as a template argument (or bake its return type into save_it_for_later). Something like

int main(void) {
   ...
   save_it_for_later2<foo> saved = {t};
   ...
}

使用宏包装 foo 来提取所需的类型,我也同样可以:

I'd be equally fine with some sort of macro wrapping foo to extract the required types:

int main(void) {
   ...
   save_it_for_later<MACRO_USING_DECLTYPE_OR_SOMESUCH(foo)> saved = {t};
   ...
}

这种担忧似乎与最初的问题正交,足以保证其有据可依.

This concern seems orthogonal enough to the original question to warrant its 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);
    // ...
}

这篇关于提取函数参数类型作为参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆