C++ Lambda 作为函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8109571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lambda as function parameter
提问by slartibartfast
What's the notation for declaring a lambda variable, or function parameter, without the use of auto
or templates? Is there any way to do so? Or does the compiler define a unique class object for each lambda whose name is unknown to the programmer before compile time? If so, why? Can't they just be passed as some sort of function pointer? It would be a major disappointment if that were not possible.
在不使用auto
或模板的情况下声明 lambda 变量或函数参数的符号是什么?有什么办法吗?或者编译器是否为每个 lambda 定义了一个唯一的类对象,其名称在编译之前程序员是未知的?如果是这样,为什么?它们不能作为某种函数指针传递吗?如果这是不可能的,那将是一个重大的失望。
采纳答案by Todd Gardner
Lambdas may hold state (like captured references from the surrounding context); if they don't, they can be stored in a function pointer. If they do, they have to be stored as a function object (because there is no where to keep state in a function pointer).
Lambda 可以保持状态(例如从周围上下文中捕获的引用);如果没有,它们可以存储在函数指针中。如果他们这样做,他们必须被存储为一个函数对象(因为在函数指针中没有保存状态的地方)。
// No state, can be a function pointer:
int (*func_pointer) (int) = [](int a) { return a; };
// One with state:
int b = 3;
std::function<int (int)> func_obj = [&](int a) { return a*b; };
回答by David Alber
You can use a polymorphic wrapper for a function object. For example:
#include <functional>
std::function<double (double, double)> f = [](double a, double b) { return a*b };