I am a c++ newbie so I'm not sure how to write this, but basically I want a function that takes in a few parameters and returns a function pointer that does not need any parameters and can be executed for later use. Exactly like a closure.
I know c++ does not have closures, but can get some of the same effects with lambda expessions. I'm just not sure if it can do what I want it to do. Again I don't know much c++. I have been going through tutorials and reading posts about how lambdas work in c++, but I can't figure out how do get this code to work.
Here is some example code of what I'm trying to in 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();
This is what I want in c++, but it's wrong
// 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();
}
And here is what I have in c++, works, but cannot take in parameter
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();
}
I appreciate any responses in advance!