C ++设置回调函数

时间:2015-02-04 14:47:49

标签: c++ callback

我正在运行一个自定义网络服务器的程序,该服务器应该输出一些活动的HTML内容:

// This is the webserver library...
class myWebServer
{
public:
    myWebServer() {}
    ~myWebServer() {}

    // ...

    void sendPageToClient()
    {
        // ... "client" is the TCP socket
        // ... "html" should contain the output of myMainProgram::ProcessASP

        client->send(html);
    }

    void runServer()
    {
        while (1)
        {
            // listens to TCP socket
            client->listen();

            // receive query from browser
            // send HTML using sendPageToClient()
            // ...
            sendPageToClient();
        }
    }
};


// This is the main program class...
class myMainProgram
{
public:
    myMainProgram() {}
    ~myMainProgram() {}

    // ...

    string ProcessASP(string query)
    {
        return
        "<html>The query string you have passed contains:<br>"
        + query +
        "</html>";
    }

    void runProgram()
    {
        // do something
    }
};


// This is a multi-threaded application
void main()
{
    myMainProgram   myProgram;
    myWebServer myServer;

    myProgram.runProgram();
    myServer.runServer();
};

如何设置一个回调函数,该函数来自类myWebServer调用myMainProgram::ProcessASP传递参数并接收其输出?

1 个答案:

答案 0 :(得分:2)

您可能想要使用std::function<std::string(std::string)>

class myWebServer {
    // not really a "callback"?
    std::function<std::string(std::string)> callback;

public:
    template <typename F>
    void setCallback(F&& f) { callback = std::forward<F>(f); }

    void runServer() {
      // ...
      std::string foo = callback("hello");
      // do something with foo
    }
};

然后,你可以这样做:

myServer.setCallback([&](std::string query){
    return myProgram.ProcessASP(query);
});