我想创建一个std :: vector对象(或任何其他标准或自定义容器类型)与自定义和任意函数的元素签名都是相同的。如何在不明确定义函数的情况下创建函数的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
)是可以的。但是,这样做(如使用升压,QT或任何其他文库或框架)的非标准的方式不是优选的。
你甚至不需要在这里使用'function'(除非你使用VC2010)。无捕获的lambda优雅地降级到函数指针。然而,如果你想使用除函数指针以外的东西,总是使用'function'。 – 2011-12-27 19:15:26