Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

function - How to make static callback c++

I have two files, the main one and a class. I want to call a function inside the class(void) and from inside that function call another in the main. Before a lot of searching I found way to do so with a callback and the code ended up like this:

File

#include <functional>
#include <iostream>

class Foo 
{
public:
    std::function<void()> onCallBackResult;
    void start(std::function<void()> callback)
    {
        onCallBackResult = callback;
        second();
    }
    void second() { //Needs to be static here
        onCallBackResult();
    }
};

void onCallBackResult() 
{
    std::cout << "Result
";
}

int main() {
    Foo foo;
    foo.start(std::bind(onCallBackResult));
}

And it works kinda well, but the problem is that I really need to make the start static because it work with WndProc from the Windows api but I cannot make the onCallBackResult from the class static too because so I want to know if is there a way to fix this or any other way to call a function from the main.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All you need is a prototype. None of that mechanism (std::bind, std::function) is needed. In "Foo.h":

void onCallBackResult();

And then change the function to call that one:

void start()
{
//Do some tasks
onCallBackResult();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...