c++ std::vector 函数作为 class 方法的参数传递

c++ std::vector of functions passed as a parameter of a class method

(1) 如何创建一个 std::vector 函数,以便可以执行如下操作:

int main ()
{
    std::vector<????> vector_of_functions;
    // Add an adding function into the vector
    vector_of_functions.push_back(
        double function (double a, double b) {
            return a + b
        }
    );
    // Add a multiplying function into the vector
    vector_of_functions.push_back(
        double function (double a, double b) {
            return a * b;
        }
    );

    //  Use the functions
    std::cout << "5 + 7 = " << vector_of_functions[0](5, 7); // >>> 5 + 7 = 12
    std::cout << "5 * 7 = " << vector_of_functions[1](5, 7); // >>> 5 * 7 = 35

    return 0;
}

虽然我希望函数 return 和参数可以是任何类型,但不一定是。定型的话我也可以

(2) 怎么把那种std::vector作为函数的参数传递给函数。

void func (std::vector<???> vof) {
    std::cout << vof[0](5, 7);
};
int main ()
{
    std::vector<????> vector_of_functions;
    // Add an adding function into the vector
    vector_of_functions.push_back(
        double function (double a, double b) {
            return a + b
        }
    );
    // Add a multiplying function into the vector
    vector_of_functions.push_back(
        double function (double a, double b) {
            return a * b;
        }
    );

    //  Call the function
    func( vector_of_functions ); // >>> 12

    return 0;
}

(3) 除了函数是头文件中定义的 class 的方法外,我该如何做同样的事情。 .cpp 代码将与以前相同,只是函数将是 void ClassName::func(...); .h 代码将是这样的:

class ClassName {
    public:
        ClassName();
        void func(????);
}

使用 std::function<double(double,double)> 作为向量的模板参数,然后使用 std::function<double(double,double)> 对象或可以转换为 std::function<double(double,double)> 的对象,例如 lamda:例如 [](double a, double b) -> double { return a + b; }.

如果你可以使用 C++11+,那么你可以使用 std::function and std::bind, or lambda

所以,类似于:

using func = std::function<double(double, double)>;
using vfuncs = std::vector<func>;

vfuncs vf;
vf.push_back([](double first, double second) { return first + second; });
vf.push_back([](double first, double second) { return first * second; });
/* obj is some function, which member function you want to call */
vf.push_back([&obj](double first, double second) { return obj.op(first, second); });