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

时间:2018-12-11 14:08:09

标签: c++ function class pointers 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;
}

虽然我想函数的返回值和参数可以是任何类型,但不必一定是。如果它们是固定类型,我很好。

(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)除了函数是头文件中定义的类的方法之外,我该如何做。 .cpp代码与以前的代码相同,不同之处在于该函数为void ClassName::func(...); .h代码将如下所示:

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

2 个答案:

答案 0 :(得分:5)

如果可以使用C ++ 11 +,则可以使用std::functionstd::bindlambda

所以,像这样:

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); });

答案 1 :(得分:1)

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