简体   繁体   English

作为参数传递的C ++调用方法

[英]C++ call method passed as argument

I have a Session class that defines multiple Send methods that takes different arguments. 我有一个Session类,定义了多个采用不同参数的Send方法。 For example: 例如:

class Session
{
public:
    void SendInt(int i);
    void SendTwoInts(int i1, int i2);
    void SendStringAndInt(const std::string& str, int i);
};

Also I have SessionsManager class that holds all sessions. 我也拥有保存所有会话的SessionsManager类。

class SessionsManager
{
private:
    std::vector<Session*> m_Sessions;
    ...
};

I'd like to add broadcast methods to SessionsManager class that calls the same method for each session. 我想向每个会话调用相同方法的SessionsManager类添加广播方法。 If I just define a separate broadcast method for each Session Send method I will end like: 如果我仅为每个会话发送方法定义一个单独的广播方法,我将结束:

class SessionsManager
{
public:
     void BroadcastInt(int i) { for(auto it : m_Sessions) { it->SendInt(i); } };
     void BroadcastTwoInts(int i1, int i2) { for(auto it : m_Sessions) { it->SendTwoInts(i1, i2); } };
...
};

It is too much copy-paste and in theory the number of Send methods will grow in the future. 复制粘贴太多,理论上,Send方法的数量在将来会增加。 I'd like something smarter. 我想要更聪明的东西。

In the perfect scenario I imagine having templated Broadcast method that takes Session method and its arguments as arguments, ie something like: 在理想的情况下,我设想有一个模板化的Broadcast方法,该方法将Session方法及其参数作为参数,例如:

template<typename Method, typename ...Args)
void Broadcast(Method, Args ... args)
{
...
}

and the broadcast call will be 广播呼叫将是

Broadcast(&Session::SendInt, 2);
Broadcast(&Session::SendTwoInts, 2, 3);

The problem is that I am not sure if it is possible and how exactly to implement Broadcast. 问题是我不确定是否有可能以及如何准确实现广播。 I am thinking around std::function and std::bind but still I am unable to compile my code. 我在考虑std :: function和std :: bind,但是仍然无法编译我的代码。

Any ideas are welcome. 任何想法都欢迎。

  • UPDATED 更新

It is possible to have 2 Send methods with the same arguments but with different semantic. 可能有2个具有相同参数但语义不同的Send方法。 For example: 例如:

void SendName(const std::string& name);
void SendDescription(const std::string& description);

Honestly I would solve this by using a variadic template for Broadcast , and simply overload the Send() method for different arguments. 老实说,我将通过使用一个用于Broadcast的可变参数模板来解决此问题,并简单地为不同的参数重载Send()方法。

Here is the code: 这是代码:

#include <vector>
#include <string>

class Session
{
public:

    void Send(int i) { }
    void Send(int i1, int i2) { }
    void Send(const std::string& str, int i) { }
};

class SessionsManager
{

public:

    template<typename... Args>
    void Broadcast(Args&&... args)
    {
        for(auto it : m_Sessions)
        {
            it->Send(std::forward<Args>(args)...);
        }
    }

private:

     std::vector<Session*> m_Sessions;

};

Here is how you would use it: 这是您将如何使用它:

int main()
{
    SessionsManager sm;
    sm.Broadcast(1, 2);
    sm.Broadcast(1);
    sm.Broadcast("Hello", 2);
}

And here is a live example . 这是一个生动的例子


UPDATE: 更新:

Provided you really cannot afford overloading, this solution meets your original requirements: 如果您真的负担不起过载,那么此解决方案可以满足您的原始要求:

#include <vector>
#include <string>

class Session
{
public:

    void SendInt(int i) { }
    void SendTwoInts(int i1, int i2) { }
    void SendStringAndInt(const std::string& str, int i) { }
};

class SessionsManager
{
public:

    template<typename M, typename... Args>
    void Broadcast(M m, Args&&... args)
    {
        for(auto it : m_Sessions)
        {
            ((*it).*m)(std::forward<Args>(args)...);
        }
    }

private:

     std::vector<Session*> m_Sessions; // You could use shared_ptr<> here

};

This is how you would use it: 这是您将如何使用它:

int main()
{
    SessionsManager sm;
    sm.Broadcast(&Session::SendTwoInts, 1, 2);
    sm.Broadcast(&Session::SendInt, 1);
    sm.Broadcast(&Session::SendStringAndInt, "Hello", 1);
}

And here is a live example . 这是一个生动的例子

A solution with std::bind could look like 使用std::bind解决方案可能看起来像

#include <iostream> 
#include <functional> 
#include <vector> 

class Session
{
public:
    void SendInt(int i){ std::cout << i; }
    void SendTwoInts(int i1, int i2){ std::cout << i1;}
};

class SessionsManager
{
public:
   std::vector<Session*> m_Sessions;
    template<typename T, typename ...Args>
    void Broadcast(T f, Args&& ...args) {
        for (auto it : m_Sessions) {
            std::bind(f, it, std::forward<Args>(args)...)();
        }
    }
};


int main() {
   SessionsManager m;
   m.m_Sessions.push_back(new Session());
   m.m_Sessions.push_back(new Session());
   m.Broadcast(&Session::SendInt, 2);
   m.Broadcast(&Session::SendTwoInts, 3, 2);
}

I don't know what you are really trying to achive. 我不知道您到底要达到什么目标。 It looks like one SessionsManager have multiple Sessions . 看起来one SessionsManager have multiple Sessions Performing an action on SessionManager relays that action to all its Session s SessionManager上执行操作会将该操作中继到其所有Session

and you have a Broadcaster that sends commands to SessionManager 并且您有一个将命令发送到SessionManager的广播SessionManager

struct SessionManager{
   template <typename F>
   void broadcast(F f){
     std::for_each(m_sessions.begin(), m_sessions.end(), f);
   }

   std::vector<Session*> m_sessions;
};

Now you do boost::bind and send them to SessionManager::broadcast 现在,您进行boost::bind并将其发送到SessionManager::broadcast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM