c++ - 如何在不显式定义函数的情况下创建函数的 std::vector?

标签 c++ vector functional-programming function-pointers 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));
}

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

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)的实现是可以的。但是,不推荐使用非标准方法(例如使用 BoostQT 或任何其他库或框架)。

最佳答案

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

关于c++ - 如何在不显式定义函数的情况下创建函数的 std::vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648261/

相关文章:

functional-programming - 是否有一种不那么冗长的方式来解开 Elm 中的值

c++ - 为什么具有无用的隔离 `static` 的函数被认为是不纯的?

scala - 什么是 : "operation of a program should map input values to output values rather than change data in place" 的好例子

c++ - Boost.Regex 奇怪之处

python - Qt:从一个 QSqlTableModel 在两个 QListView 之间移动条目

c++ - 如何释放指针 vector ?

c++ - 如何将 vector 转换为特定类型的字符串

C++ - 在初始化类成员之前运行一个函数

c++ - 通过重载格式化链表输出 <<

c++ - 如何用 C++ 编写高效的遗传算法