c ++ std ::作为类方法的参数传递的函数的向量

Ell*_*mas 0 c++ pointers class function stdvector

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

虽然我想如果函数返回和参数可以是任何类型,它不一定是.我很好,如果他们是一个集合类型.

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

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

class ClassName {
    public:
        ClassName();
        void func(????);
}
Run Code Online (Sandbox Code Playgroud)

For*_*veR 5

如果你可以使用C++ 11 +,那么你可以使用std :: functionstd :: bind,或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); });
Run Code Online (Sandbox Code Playgroud)