【问题标题】:c++ std::vector of functions passed as a parameter of a class methodc++ std::vector 作为类方法的参数传递的函数
【发布时间】:2018-12-11 14:08:08
【问题描述】:

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

【问题讨论】:

标签: c++ function class pointers stdvector


【解决方案1】:

如果可以使用 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); });

【讨论】:

  • 这比我的回答好,应该被接受。
  • 谢谢。当我将 using vfuncs = std::vector&lt;func&gt;; 更改为 std::vector&lt;func&gt; vfuncs; 时,此方法有效
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多