c++ - 提取函数参数类型作为参数包

标签 c++ c++11 function-pointers variadic-templates

这是 "unpacking" a tuple to call a matching function pointer 的后续问题,它询问如何以通用方式将 std::tuple 中的值作为参数提供给函数。给出的解决方案如下:

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;
}

我的问题是是否有办法制作 save_it_for_later 的替代版本,它只采用 foo 作为模板参数,这样我们就不必提供 foo 的参数类型作为模板参数(或将其返回类型烘焙到 save_it_for_later 中)。有点像

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

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

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

这个问题似乎与原始问题正交,足以保证自己的票。

最佳答案

#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);
    // ...
}

关于c++ - 提取函数参数类型作为参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926764/

相关文章:

c++ - 编译时数学函数的 constexpr vs 模板?

c++ - std::thread 通过引用传递 vector 元素

c - 如何使用位于结构中的函数指针来运行函数? (C)

function - Lua - 执行存储在表中的函数

c++ - 在VS2017中编译错误C2027,但使用小对象优化的Clang则不然

c++ - 在 C++ 中使用排序谓词

c++ - C++ 中的并行循环

c++ - boost .Python : Ownership of pointer variables

c++ - 基类中的模板化类成员,不存在于派生类中

c++ - 如何在 C++ 中重新传递函数指针