[DiscordArchive] What's the right way to call CSMH's SendServerResponse from C++?
[DiscordArchive] What's the right way to call CSMH's SendServerResponse from C++?
Archived author: whatwere • Posted: 2022-07-09T19:36:09.137000+00:00
Original source
What's the right way to call CSMH's SendServerResponse from C++?
Archived author: Intemporel • Posted: 2022-07-09T19:46:27.025000+00:00
Original source
Finally my dream come true, i can do this :
```cpp
class A
{
public:
...
void setFunction(std::function<void()> param)
{
my_access = param;
}
void run()
{
...
my_access();
}
private:
std::function<void()> my_access;
}
class B
{
public:
void anotherFunc()
{
A* myclassA = new A();
std::function<void()> func1 = [this]() {
std::cout << "Hello" << std::endl;
};
std::function<void()> func2 = [this]() {
std::cout << "Bye bye" << std::endl;
};
myClassA->setFunction(func1);
myClassA->run(); // return <Hello>
myClassB->setFunction(func2);
myClassB->run(); // return <Bye bye>
}
}
```
Archived author: <o> • Posted: 2022-07-09T19:48:25.864000+00:00
Original source
if they don't have to be member functions then yeah, you can capture scope variables (including "this") like that
Archived author: Intemporel • Posted: 2022-07-09T19:49:27.469000+00:00
Original source
i can do this because `std::function<>` is a type, i can capture any object like that, add any param etc... it's work
Archived author: <o> • Posted: 2022-07-09T19:53:02.172000+00:00
Original source
that's the magic you normally get with std functions, but just be careful so you actually keep the reference around because that is not ensured (i.e. you'll crash if the B variable goes out of scope and you try to call the function).
Archived author: <o> • Posted: 2022-07-09T19:54:12.937000+00:00
Original source
you can also capture other variables like that, both by value and by reference:
```c++
int val1 = 0;
std::function<void()> f0 = [val1]() { std::cout << val1 << "\n"; }
std::function<void()> f1 = [&val1]() { std::cout << val1 << "\n"; }
```
Archived author: <o> • Posted: 2022-07-09T19:55:12.068000+00:00
Original source
capture by value and the lambda will itself keep a copy of the variable in its own scope, but that doesn't help if it's just a pointer of course
Archived author: Intemporel • Posted: 2022-07-09T20:04:37.922000+00:00
Original source
Class A is initialised and used only by and in class B, in this way i think i can't go out of scope, generally i only need to capture this