繁体   English   中英

如何从通用模板<typename T>中提取lambda的Return Type和Variadic Parameters Pack

[英]How to extract lambda's Return Type and Variadic Parameters Pack back from general template<typename T>

我想创建一个模板化的类或函数,它接收一个lambda,并将它放在std :: function <>内部.Lambda可以有任意数量的输入参数[](int a,float b,...)std :: function <>应该对应lambda的operator()的类型

template <typename T> 
void getLambda(T t) {
   // typedef lambda_traits::ret_type RetType; ??
   // typedef lambda_traits::param_tuple --> somehow back to parameter pack Args...
   std::function<RetType(Args...)> fun(t);
}

int main() {
    int x = 0;
    getLambda([&x](int a, float b, Person c){}); 
}

所以我需要以某种方式提取返回类型和参数包

这里的答案建议在lambda的:: operator()上使用部分规范

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())>
{};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    enum { arity = sizeof...(Args) };
    // arity is the number of arguments.

    typedef ReturnType result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
        // the i-th argument is equivalent to the i-th tuple element of a tuple
        // composed of those arguments.
    };
};

但我需要一种方法将元组<>转换回参数包,以创建一个正确的std :: function <>实例化

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())>
{};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
    using result_type = ReturnType;
    using arg_tuple = std::tuple<Args...>;
    static constexpr auto arity = sizeof...(Args);
};

template <class F, std::size_t ... Is, class T>
auto lambda_to_func_impl(F f, std::index_sequence<Is...>, T) {
    return std::function<typename T::result_type(std::tuple_element_t<Is, typename T::arg_tuple>...)>(f);
}

template <class F>
auto lambda_to_func(F f) {
    using traits = function_traits<F>;
    return lambda_to_func_impl(f, std::make_index_sequence<traits::arity>{}, traits{});
}

上面的代码应该做你想要的。 如您所见,主要思想是创建一个整数包。 这是variadics的非类型模板。 我不知道你可以使用这种方法而不调用另一个函数的任何技术,所以通常在这些带有元组的情况下你会看到一个嵌套的“impl”函数来完成所有的工作。 获得整数包之后,在访问元组时展开它(用于获取值)。

在风格上注意:使用using而不是typename尤其是在模板繁重的代码中,因为前者也可以使用别名模板。 并且不使用该enum技巧来存储静态值而不使用空间; 编译器无论如何都会优化它,只需使用static constexpr整数static constexpr清楚了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM