簡體   English   中英

我可以使用lambda指針數組來保存具有不同類型的參數/返回值的函數嗎?

[英]Can I have an array of lambda pointers in order to hold functions with different types of arguments/return values?

假設我有一個包含兩個成員函數的類:

#include <string>
#include <vector>

using namespace std;

class MyClass{
  MyClass(){
    MyCommandServer server;
    server.addToCollection(&[](string a)->string{return helloWorld();});
    server.addToCollection(&[](string a)->string{return to_string(add(stoi(a[0]),stoi(a[1])));});

    while(true){
      server.pollForCommand();
      doSomethingElse();
    }
  }

  string helloWorld(){
    return "Hello World!";
  }

  int add(int a, int b){
    return a+b;
  }
};

在第一個實例中實例化的另一個類:

typedef string (*MyFunctionPointer)(string);

class MyCommandServer{
  MyCommandServer(){}

  void addToCollection(MyFunctionPointer ptr){
    functionCollection.push_back(ptr);
  }

  void pollForCommand(){
    string newCommand = checkForCommand(&args);
    if(newCommand.size()&&isValidCommand(newCommand[0])){
      sendResponseToClient(functionCollection[newCommand[0]](newCommand.substr(1)));
    }
  }

  string checkForCommand();
  bool isValidCommand(char);
  void sendResponseToClient(string);
  vector<MyFunctionPointer> functionCollection;
};

我如何將前兩個方法傳遞給addToCollection(MyFunctionPointer)? 我想知道是否可以按照示例進行操作。 我的目標是要有一種僅在容器中使用索引調用MyClass函數的方法,並通過提供的lambda函數弄清楚如何使用提供的參數(如果有的話)。 這應該啟用Command Server類,在該類中,通過UDP將char作為所述索引,並將參數(如果有)作為字符串。

但是,編譯器不允許我傳遞對lambda的引用。

在MyServerClass中創建一個switch-case語句是不可行的,因為Server類不知道其父方法,因此我在該示例中手動輸入了在示例中放入lambda的代碼。

是否有可能提供與示例類似的內容?

抱歉,如果該帖子沒有達到標准,這是我的第一篇文章。

謝謝你的幫助!

lambda方法不起作用的原因是,如果lambda沒有捕獲,則只能將lambda轉換為函數指針。 但是,要在lambda中使用/包裝(非靜態)成員函數,lambda必須捕獲(存儲)特定的對象實例以在( this )上調用該成員函數,並且函數指針不能存儲(非全局)這樣的狀態。 如果添加this到捕獲列表,那么lambda表達式本身是有效的,但不能再衰減函數指針。

std::function允許您存儲任意可調用對象-甚至包括捕獲對象。 它們也比函數指針更具可讀性(並且層次更高)。

using MyFunctionType = std::function<std::string(std::string)>;

class MyCommandServer
{
  void addToCollection(MyFunctionType fnc){
    functionCollection.push_back(fnc);
  }

  // ...

  vector<MyFunctionType> functionCollection;
}

現在, MyCommandServer可以接受並存儲您的lambda(如果您按值傳遞它們),因為可以使用字符串參數調用它們並返回一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM