1

I was trying to assign a non-static function to a variable in C++. I have two functions, which are onMessageReceived and enableCommand. Here are definitions:

NetworkUtil.h:

class NetworkUtil{
public:
    std::function<void(char* message)> onMessageReceived;
    void enableCommand(char* cmd);
private:
// some private variables
}

NetworkUtil.cpp:

void NetworkUtil::enableCommand(char* cmd) {
    if (strcmp(cmd, "INIT_ACK") == 0){
        mCreateEnabled = true;
    }
    else if (strcmp(cmd, "START_ACK")){
        mStartEnabled = true;

    }
    else{
        std::cerr << "Unknown Command: " << cmd << std::endl;
    }
}

Here is a program that assigns a function to a variable:

void NetworkUtil::onMessage(WebSocket* ws, const WebSocket::Data &data)
{
// not working
    onMessageReceived = &(NetworkUtil::enableCommand);
// not working either
    onMessageReceived = std::bind(&NetworkUtil::enableCommand, data.bytes);
}

I tried both, but non of them are working. Can I get some advice on assigning a non-static function to a variable?

Peter Hwang
  • 971
  • 1
  • 12
  • 25

2 Answers2

1

Try to do like this:

onMessageReceived = std::bind(&NetworkUtil::enableCommand, this, _1);
JerryYoung
  • 267
  • 1
  • 3
0

Since you're using std::function (hence C++11 or later), I assume you can give lambda functions a try:

// Create a local variable for capturing purposes.
// You must make sure the source data is never outlived by the callback
// to avoid the "use after free" scenario.
auto bytes = data.bytes;
onMessageReceived = [=](char * message) { this->enableCommand(bytes); };

= means to capture everything actually used by the closure by value (including the value of the this pointer), and due to use of type erasure you can assign it to a signature-compatible std::function.

UnknownGosu
  • 854
  • 6
  • 9