从这个问题开始(有没有办法找出Lambda的参数类型和返回类型?),我经常使用建议的 function_traits
。然而,随着C++14的多态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.
};
};
如其他问题的答案所提出的operator()
,现在已经被重载并按照标准支持以下功能:
auto lambda1 = [](auto& a) { a.foo(); }
并且
auto lambda2 = [](auto&&... args) { foo(args...); };
现在这种重载会使function_traits
类分崩离析,因为编译器无法解析operator()
的正确版本。
lambda.cpp:98:38: error: reference to overloaded function could not be
resolved; did you mean to call it?
typedef function_traits<decltype(&T::operator())> caller;
在C++14中,是否有办法对多态lambda实现function_traits
的功能?
operator()
的参数类型,以便能够知道其返回类型,因为每个重载可能会返回不同类型的值。请注意,这里只是翻译,没有解释或添加额外内容。 - Jarod42std::result_of
也能获取到这些信息。可能需要与C++11版本进行更新,但它仍然可能有效。 - rubenvbtemplate <typename L, typename...Ts> void foo(L lambda, Ts&&... args) { ... }
获取lambda和传递的参数,因此我可能知道lambda的参数类型,但不知道它如何等待它们(作为引用或值)。 - Michael Haidldecltype(lambda(std::forward<Ts>(args)...))
是返回类型。获取参数类型需要另一个特性(需要编译器魔法),这在 C++14 中是不可用的。(它需要库基础1 TS中的调用类型特性)。 - T.C.