std :: function vs Lambda用于传递成员函数

Pot*_*tat 4 c++ lambda pointers c++11

我正在为游戏引擎创建消息传递系统,其中引擎的最终用户可以创建消息对象并将其传递给游戏对象,以由包含附加到游戏对象的组件的侦听器对象进行解释.如果消息与侦听器正在侦听的消息匹配,则侦听器应调用函数指针并将其传递给已接收的消息.基本结构看起来像这样:

class Message
{
    std::string message;
};

class Listener
{
    std::string target;
    void (*fn)(Message*);
};
Run Code Online (Sandbox Code Playgroud)

使用游戏对象的代码来接收如下所示的消息:

//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's function
            jtemp->function(newMessage);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,由于上面的代码片段需要调用的函数是组件类型的成员函数,因此我无法设置Listener.fn为相等Component::foo或任何其他函数.

我问我的同学,看看他们是否可以提供任何建议,我收到的两条建议是使用lambdas或用于std::function将成员函数指针转换为常规函数指针.

我之前从未使用过lambda函数,但是在这里研究之后,如果我正确地把握它,似乎每次我传递一条消息时都会写一个新的lambda,这会破坏使用像这样的系统的目的.和研究后,std::function 在这里,在这里,并在这里好像std::function会给我,我需要落实,但已给了我大量错误的灵活性

我是否忽略了lambdas的力量,如果我std::function在这种情况下使用a ,如果是这样,怎么能创建一个返回void并获取消息指针?

Yak*_*ont 5

std::function是适合存储的解决方案. std::function几乎存储任何与其签名兼容的东西.

通常你会用lambda填充它.因为这比bind其他替代方案更容易和更清晰.

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

fn = [comp](Message * m){ comp->foo(m); };
Run Code Online (Sandbox Code Playgroud)