C++执行函数和 lambda 内部
C++ executing function and lambda inside
我正在尝试在c ++中运行与此python代码类似的代码。
def f1(a):
def f2(b):
return a*b
return f2
#
if __name__== '__main__':
x=f1(3)(4)
print('Result = {0}'.format(x))
输出 : Result = 12
C++年,
#include<iostream>
#include<vector>
#include <functional>
int f1(int &x)
//should I return lambda from function ? std::function<decltype (...) f1?
{
return [x](int &y) ->int
{return x * y;} ;
}
int main()
{
int y = { 3 }, z = { 4 };
int x=f1(y)(z);
std::cout<<x<<"n";
return 0;
}
但我不知道正确的方法。有人可以评论吗?
试试这个,也许?
#include <iostream>
#include <vector>
#include <functional>
std::function<int (int&)> f1 (int& x)
{
return [x] (int& y) -> int {
return x * y;
};
}
int main ()
{
int y = { 3 }, z = { 4 };
int x = f1(y)(z);
std::cout << x << "n";
return 0;
}
由于f1
是一个高阶函数,因此需要使其返回一个函数。 std::function
将任何可以作为函数调用的内容(其模板参数中指定的签名(包装成可以传递的值,因此这是返回类型的良好候选项。
如果要将两个值传递给 f1,如下所示:
#include <iostream>
#include <vector>
#include <functional>
std::function<int ()> f1 (int& x, int& y)
{
return [x, y] () -> int {
return x * y;
};
}
int main ()
{
int y = { 3 }, z = { 4 };
int x = f1(y, z)();
std::cout << x << "n";
return 0;
}
在这种情况下,返回的函数在调用时不会接受任何参数,因为这两个值都已在 lambda 中捕获。
相关文章:
- 如何修改 lambda 内部字符串的向量
- 如何在C++中传递lambda函数内部的对象实例
- 当使用lambda进行变量的复杂初始化时,如何处理从内部抛出的lambda外部异常
- 访问lambda内部循环控制变量
- "如果 constexpr",在 lambda 内部,在包扩展内部 - 编译器错误?
- C++执行函数和 lambda 内部
- C++14 使用捕获说明符递增 lambda 函数内部的值
- lambda内部捕获的constexpr变量失去了其constexpr-ness
- 从 lambda 内部返回 C++11 中的 lambda 类型(平面映射函数)
- Constexpr变量在Lambda内部未初始化
- 按值或引用在lambda内部分配指针值
- sizeof可以应用于未捕获的变量的lambda内部吗?还是这是一个编译器错误?
- lambda内部引用捕获对象的类型
- 显式操作符bool未在lambda内部调用- MSVC错误
- c++ 11变量捕获与lambda内部的另一个lambda
- 如何从lambda内部的函数返回
- 捕获和调试对移动lambda内部局部变量引用的无效使用
- 将lambda传递给对象并在lambda内部修改该对象
- 创建新线程时在lambda内部使用unique_ptr的线程安全性
- C++11 是否允许在 lambda 内部和 lambda 中进行以下嵌套的可变参数展开