你能用参数制作函数向量吗?
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;
}
这有效,但不是我需要的。
正确的版本是一个具有参数的函数: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;
}
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用向量的template_back函数
- 如何通过派生类函数更改基类中的向量
- 变量没有改变?通过向量的函数调用
- 一对向量构造函数:初始值设定项列表与显式构造
- 在c++中使用向量时,如何调用构造函数和析构函数
- std::sort()函数无法对向量的一部分进行排序
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- C++中函数的向量返回类型引发错误
- 添加存储在向量中的大整数的函数出现问题
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 具有 lambda 函数的函数向量
- 你能用参数制作函数向量吗?
- 在C++中使用成员函数向量时,有没有办法实现协变返回类型
- 在编写 lambda 函数向量时出现隔离错误
- 如何在 boost.process 间共享内存中使用复杂结构"push_back"函数向量
- 是否将std矢量重新分配到默认的构造函数向量是擦除的好方法
- 运行提升for_each中的成员函数向量
- 创建和回推函数向量
- C++,指向函数向量的指针的STL映射