Std :: function vs Lambda to pass member functions

I am creating a messaging system for a game engine, where the end user of the engine can create a message object and pass it to the game object, which will be interpreted by listener objects containing components attached to the game object. if the message corresponds to the message that the listener is listening to, the listener must call the function pointer and pass the message that was received to it. The basic structure looks something like this:

class Message
{
    std::string message;
};

class Listener
{
    std::string target;
    void (*fn)(Message*);
};

with a game object code to get a message that looks something like this:

//if the queue is empty then dont do anything
if (messageQueue.empty())
{
    return;
}

//else grab the front of the queue
Message* newMessage = messageQueue.front();

//pop our message from the queue
messageQueue.pop();

//for each component in our list
for (std::vector<Component*>::iterator i = ComponentList.begin(); i < ComponentList.end(); i++)
{
    Component* itemp = *i;
    //for each message in its listener list
    for (std::vector<Listener*>::iterator j = itemp->Listeners.begin(); j < itemp->Listeners.end(); j++)
    {
        Listener* jtemp = *j;
        //check the listener against the newMessage
        if (jtemp->name == newMessage->name)
        {
            //call jtemp function
            jtemp->function(newMessage);
        }
    }
}

, , , , , - , Listener.fn Component::foo .

, - , , , lambdas, std::function - .

-, , , , lambda , , . std::function , , std::function , , .

lambdas, std::function , , , void ?

+4
2

std::function - . std::function , .

. , bind .

std::function<void(Message*)> fn;

fn = [comp](Message * m){ comp->foo(m); };
+4

, , "" , ++ 11. - ++ - ... ... . :/

, std::function . -, (-), . std::function, , , , x)

, ( , ++):
https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types

0

Source: https://habr.com/ru/post/1654224/


All Articles