如何保存函数指针以供以后在c++中使用,类似的闭包具有保存状态



我是一个c++新手,所以我不确定如何写这个,但基本上我想要一个函数,接受几个参数,并返回一个函数指针,不需要任何参数,可以执行供以后使用。就像闭包一样

我知道c++没有闭包,但是可以用lambda表达式获得一些相同的效果。我只是不确定它能不能做我想让它做的事。再说一次,我不太懂c++。我一直在通过教程和阅读有关lambda如何在c++中工作的帖子,但我不知道如何让这些代码工作。

下面是我在typescript

中尝试的一些示例代码
let myVariable;
const myClosure = (param1: number, param2: number, param3, string, ) => {
return () => {
// Do something with params
console.log(param1, param2, param3);
}
}
function whereInitalized() {
myVariable = myClosure(1,2,"name");
}
function whereExecuted() {
myVariable(); // prints the params
}
whereInitalized();
whereExecuted();

这是我在c++中想要的,但是它是错误的

// Not correct syntax or type
// Having trouble getting typing for this variable;
std::function<void(param1: T, param2: P, param3: V)> (*myVariable)() = myClosure;
std::function<void()> myClosure(param1: T, param2: P, param3: V) {
return []() { // Returns a function that does not take a parameter
param1.someMethod();
param2->Call(blah, blah);
// ... More work

};
}
void functionWhereInitalized() {
myVariable = myClosure(param1, param2, param3);
}
void functionWhereExecuted() {
myVariable();
}

这是我在c++中,工作,但不能接受参数

std::function<void()> myVariable = myClosure;
std::function<void()> myClosure() {
return [num = 99]() mutable {
// Test code to see it gets called
num++; 
std::cout << num << "  --  " << "n";
};
}
void functionWhereInitalized() {
myVariable = myClosure();
}

void functionWhereExecuted() {
myVariable();
}

我感谢任何提前回应!

在回答这个技术问题之前,我同意Sam Varshavchik的一句话:

你说你"不太懂c++"。不幸的是,您将了解c++的第一件事是,它不是关于即时满足的。学习它需要时间,很长时间。你正在描述c++库中的一个基本模板,但要达到这个目标,有必要研究和学习核心的c++基础,大约一年或两年,然后才能触及其高级主题,如模板。任何阻碍这一进程的企图最终都会以失败告终。c++太复杂了,不能通过在Stackoverflow上一次问一个问题来学习。

现在对于技术问题:您可以像这里描述的那样使用lambda捕获1: 来实现简单的闭包
#include <iostream>
#include <string_view>
auto make_closure(std::ostream& out, std::string_view message, int repeat=1)
{
return [&out,repeat,message]() mutable { while (repeat --> 0) out << message; };
}
int main(){
auto say_hello = make_closure(std::cout, "Hellon", 2);
say_hello();
}

现场演示


<一口>1)

捕获是一个逗号分隔的0个或多个捕获列表,可选地从capture-default开始。捕获列表定义了可从lambda函数体内部访问的外部变量。唯一的捕获默认值是

&(通过引用隐式捕获使用的自动变量)和=(通过复制隐式捕获使用的自动变量)。如果存在捕获默认值,则可以隐式捕获当前对象(*this)。如果隐式捕获,则始终通过引用捕获,即使捕获默认值是=。当捕获默认值为=时,不建议隐式捕获*this。(因为C + + 20)

std::function<void(param1: T, param2: P, param3: V)> (*myVariable)() = myClosure;

我不太清楚这里发生了什么。我的猜想是你想做这样的事情

std::function<void()> yourClosure(T1 const& p1, T2 const& p2, T3 const& p3)
{
return [p1, p2, p3]() { /* do the thing */};
}

但是如果你只是想保存函数供以后使用你可以选择

auto const function = [a,b,c](){ /* meaningful code*/ };

some_types... a, b, c; // whatever variables you have
auto const function_with_params = [](auto const& a, auto const& b, auto const&c){ /* skrnyr dgdyr */};
auto const function_with_bound_params = std::bind(function_with_params, a, b, c);

lambda版本和binding版本都应该可以强制转换为std::function<void()>

最新更新