我正在使用 code from another answer获取 lambda 函数的类型(返回和参数)。这是答案中的相关代码:
template <typename T>
struct function_traits
: public function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its '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.
};
};
我想创建一个参数列表来自动将 lambda 转换为函数指针:
template<typename Func>
constexpr auto l2f(Func lambda) {
typedef function_traits<Func> traits;
return static_cast<traits::result_type(*)( ..all the args.. )(lambda);
}
现在我正在做的是,我向 function_traits 结构添加了一个函数:
template <typename Func>
static auto convertToFunctionPointer(Func fn) {
return static_cast<ReturnType(*)(Args...)>(fn);
}
它有效,但我真正想知道的是如何使 function_traits 中的 Args 内容可用以从外部访问它,以及如何“内联”多个模板然后展开它们。像这样的东西(不起作用):
return static_cast<traits::result_type(*)(traits::arg<std::make_index_sequence<traits::arity>...>::type...)(lambda);
最佳答案
作为Nawaz pointed out ,并非所有 lambda 都可以转换为指针,只有那些没有捕获的。对于那些没有捕获的,它们有一个隐式转换,可以通过在前面添加一个 +
来强制转换。
但要直接回答你的问题,只需在特征中为签名加上别名
template<typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...)>
{
using signature = R(Args...);
};
template<typename F>
auto cast(F f)
{
return static_cast<typename function_traits<F>::signature*>(f);
}
关于c++ - 如何使外部可访问的结构内的可变参数模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035480/