你能用参数制作函数向量吗?

Can you make a vector of functions with parameters?

本文关键字:函数 向量 数制 参数      更新时间:2023-10-16

是否可以创建一个函数被推回的向量?
我尝试过用指针做一些事情,但它仅适用于没有参数的函数。

例如

#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;
}

这有效,但不是我需要的。
正确的版本是一个具有参数的函数:void printInt(int a),您可以使用不同的值(如4-1但来自向量functionStack调用它。

如果向量中的函数具有不同的参数,则可能会更复杂,因此让我们假设每个函数都具有相同类型和数量的参数。

这个:

void (*)()

是一个带参数的函数指针。因此,请更改它以采用所需的参数。

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;
}