Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 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 Reply

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...