【发布时间】:2017-12-16 05:54:50
【问题描述】:
我正在尝试函数式编程,我写了这个。
[=](auto p) {
return [=](auto q) {
return p(q)(p);
};
})
我开始想知道这怎么可能,p 的类型是什么?
所以,我写了这样的东西。
template<class Type>
using LambdaType = std::function<std::function<Type(Type)>(Type)>;
和
[=](LambdaType<int> p) {
return [=](LambdaType<int> q) {
return p(q)(p);
};
}
编译时,编译器会报错。
error C2664: 'std::function<Type (int)> std::_Func_class<_Ret,int>::operator ()(int) const': cannot convert argument 1 from 'std::function<std::function<Type (int)> (int)>' to 'int'
error C2664: 'main::<lambda_cec7eb77d9cd29f3c40710200090f154>::()::<lambda_b8db28542cb51159223ad8d89c63d794>::()::<lambda_224126017af42fcee190e88f299089fc>::()::<lambda_415db9fd88f1008b25af42ccb33b1c77> main::<lambda_cec7eb77d9cd29f3c40710200090f154>::()::<lambda_b8db28542cb51159223ad8d89c63d794>::()::<lambda_224126017af42fcee190e88f299089fc>::operator ()(std::function<std::function<Type (std::function<std::function<int (int)> (int)>)> (std::function<std::function<int (int)> (int)>)>) const': cannot convert argument 1 from 'main::<lambda_cec7eb77d9cd29f3c40710200090f154>::()::<lambda_b8db28542cb51159223ad8d89c63d794>::()::<lambda_fa72c454c823301ba6dfa9cba6f558e0>' to 'std::function<std::function<Type (std::function<std::function<int (int)> (int)>)> (std::function<std::function<int (int)> (int)>)>'
但那时我意识到 p 只接受整数,但 p 需要是 LambdaType<LambdaType<int>> 才能接受 q
但是当你把p改成LambdaType<LambdaType<int>>时,p只接收LambdaType<int>,但p不是LambdaType<int>,它需要是LambdaType<LambdaType<LambdaType<int>>>才能接收p。
那么,p是什么类型?
顺便说一句,这是我关于stackoverflow的第一个问题
【问题讨论】:
-
在 lambda 用于评估它的上下文之前,'p' 的类型是未知的。这实际上只是编写模板函数的另一种方式。
template <typename type_of_p> auto lambda(type_of_p p)...什么是type_of_p-- 直到你真正使用它才知道。 -
如果你真的调用了那个 lambda,你会更容易看到发生了什么。
-
类型是在编译时推导出来的,取决于你使用的类型。
-
您的困惑似乎是因为 lambda 不是
std::function<SOME_SIGNATURE>类型的事实引起的