如何在不明确定义函数的情况下创建函数的std :: vector?

hkB*_*sai 4 c++ functional-programming function-pointers vector function-call

我想创建一个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));
}
Run Code Online (Sandbox Code Playgroud)

如果可能,我不想明确定义这些函数集,如下所示:

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) { /* ... */ }
};
Run Code Online (Sandbox Code Playgroud)

使用一些标准库工具(如使用std::function)的实现是可以的.但是,这样做的非标准方式(如使用Boost,QT或任何其他库或框架)不是首选.

Fre*_*son 6

听起来你想要lambda函数.如果您的C++编译器实现了C++ 11标准的这一部分,您可以直接使用它们.否则你可以使用Boost PhoenixBoost Lambda.