如何进行静态回调c ++ [英] How to make static callback c++

查看:166
本文介绍了如何进行静态回调c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,主文件和一个类。我想调用类中的一个函数(void),并从该函数内部调用main中的另一个函数。在进行大量搜索之前,我找到了一种回调方式,代码如下所示:

文件

  #include< functional> 
#include< iostream>

class Foo
{
public:
std :: function< void()> onCallBackResult;
void start(std :: function< void()> callback)
{
onCallBackResult = callback;
秒();
}
void second(){//需要在这里是静态的
onCallBackResult();
}
};

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

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

它工作得很好,但问题是我真的需要 start 静态,因为它可以从Windows API中的WndProc中工作,但是我不能从类静态创建 onCallBackResult ,因为所以我想知道是否有一种方法可以解决这个问题或其他任何方式从 main 中调用函数。



谢谢!

解决方案

您需要的只是一个原型。这种机制都不需要( std :: bind std :: function )。在Foo.h中:

  void onCallBackResult(); 

然后改变函数来调用这个函数:

  void start()
{
//执行一些任务
onCallBackResult();
}


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\n";
}

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!

解决方案

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

这篇关于如何进行静态回调c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆