我想创建一个 std::vector 对象(或任何其他标准或自定义容器类型),其中包含签名都相同的自定义和任意函数的元素。
它应该是这样的:
// Define the functions and push them into a vector
std::vector<????> MyFunctions;
MyFunctions.push_back(double(int n, float f){ return (double) f / (double) n; });
MyFunctions.push_back(double(int n, float f){ return (double) sqrt((double) f) / (double) n; });
// ...
MyFunctions.push_back(double(int n, float f){ return (double) (f * f) / (double) (n + 1); });
// Create an argument list
std::vector<std::pair<int, float>> ArgumentList;
// ...
// Evaluate the functions with the given arguments
// Suppose that it is guarantied that ArgumentList and MyFunctions are in the same size
std::vector<double> Results;
for (size_t i=0; i<MyFunctions.size(); i++)
{
Results.push_back(MyFunctions.at(i)(ArgumentList.at(i).first, ArgumentList.at(i).second));
}
如果可能的话,我不想明确定义这些函数集,如下所示:
class MyClass
{
public:
void LoadFunctions()
{
std::vector<????> MyFunctions;
MyFunctions.push_back(MyFoo_00);
MyFunctions.push_back(MyFoo_01);
MyFunctions.push_back(MyFoo_02);
// ...
MyFunctions.push_back(MyFoo_nn);
}
private:
double MyFoo_00(int n, float f) { /* ... */ }
double MyFoo_01(int n, float f) { /* ... */ }
double MyFoo_02(int n, float f) { /* ... */ }
// ...
double MyFoo_nn(int n, float f) { /* ... */ }
};
使用一些标准库工具(如使用std::function
)的实现是可以的。但是,这样做的非标准方式(如使用Boost、QT或任何其他库或框架)不是首选。