[英]Can you make a vector of functions with parameters?
是否可以創建一個功能被推回的向量?
我試過用指針做一些事情,但它只適用於沒有參數的函數。
例如,
#include <iostream>
#include <vector>
using namespace std;
void printInt();
int main()
{
vector<void (*)()> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])();
}
void printInt()
{
cout << "function works!" << 123 << endl;
}
那行得通,但不是我需要的。
正確的版本是 function ,它具有參數: void printInt(int a)
,您可以使用不同的值(例如4
或-1
)調用它,但來自向量functionStack
。
如果向量中的函數具有不同的參數,可能會更復雜,所以我們假設每個 function 具有相同類型和數量的參數。
這個:
void (*)()
是一個沒有arguments 的 function 指針。 因此,將其更改為采用所需的參數。
void (*)(int)
像這樣:
void printInt(int x)
{
cout << "function works!" << x << endl;
}
int main()
{
vector<void (*)(int)> functionStack;
functionStack.push_back(printInt);
(*functionStack[0])(123);
}
您說得對,函數必須具有相同類型和數量的參數才能有效。
你基本上已經有了。
#include <iostream>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Just needed the parameter type
vector<void (*)(int)> functionStack;
// Note that I removed the () from after the function
// This is how we get the function pointer; the () attempts to
// invoke the function
functionStack.push_back(printInt);
(*functionStack[0])(42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
這也是std::function
也可能有益的情況。
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
void printInt(int a);
int main()
{
// Similar syntax, std::function allows more flexibility at a
// lines of assembly generated cost. But it's an up-front cost
vector<std::function<void(int)>> functionStack;
functionStack.push_back(printInt);
// I don't have to de-reference a pointer anymore
functionStack[0](42);
}
void printInt(int a)
{
cout << "function works! " << a << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.