我想获取lambda的返回类型和参数类型。 Is it possible to figure out the parameter type and return type of a lambda?提供了解决方案。但这不适用于通用lambda。
template<typename F>
struct function_traits :public
function_traits<decltype(&F::operator())> {};
template<typename R,typename C,typename... Args>
struct function_traits<R(C::*)(Args...)const>:public
function_traits<R(Args...)>{
constexpr static size_t arity = sizeof...(Args);
};
auto f1 = [](int x) {return x+1; };
Print(function_traits<decltype(f1)>::arity); //return 1
auto f2 = [](auto x) {return x+1; };
Print(function_traits<decltype(f2)>::arity); //error
那么如何解决它以获得通用lambda的返回类型和参数类型?
答案 0 :(得分:3)
通用lambda是matex_test.go:26: FAIL: deserialization of a 2x3 matrice: tag 'cols' cannot be converted to int
重载是模板函数的lambda。如果推导出模板函数的参数,则它没有类型;只有这样的模板的单个实例具有类型的参数。
operator()
不是一种类型;它是一个占位符,表示“这是模板参数”。
答案 1 :(得分:1)
Lambda根本不起作用。
编译器将f1
和f2
视为具有调用运算符的类。
某些lambda具有对函数指针的隐式转换运算符。
Here is a link到cppinsights中的那两个样子。
顺便说一句,如果您不熟悉C ++模板,我高度建议使用cppinsights。 Here is a great video在谈论它,here is one在这里他使用cppinsights深入探索lambda。
我还在此处复制了相关代码以进行解释,以防万一每个链接都消失了。
这就是您的f1
的样子。
class __lambda_1_11
{
public:
inline /*constexpr */ int operator()(int x) const
{
return x + 1;
}
using retType_1_11 = int (*)(int);
inline /*constexpr */ operator retType_1_11 () const noexcept
{
return __invoke;
};
private:
static inline int __invoke(int x)
{
return x + 1;
}
};
这就是您的f2
的样子。
class __lambda_2_11
{
public:
template<class type_parameter_0_0>
inline /*constexpr */ auto operator()(type_parameter_0_0 x) const
{
return x + 1;
}
private:
template<class type_parameter_0_0>
static inline auto __invoke(type_parameter_0_0 x)
{
return x + 1;
}
};
请注意,f1
具有非模板调用运算符,并且具有对函数指针(int (*)(int)
)的隐式转换运算符。
f2
具有模板调用运算符,而没有隐式转换运算符-因为该调用运算符是成员函数模板。