当一个参数通过引用传递时,std :: function不起作用

时间:2015-10-22 05:32:38

标签: c++ c++11

我想使用std::function代替overflow-y。 如果我将以下代码中的std::vector<double>作为参考传递,编译器将生成错误。

我的代码是这样的:

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <numeric>

double add(const std::function<double(std::vector<double>)> &f, std::vector<double>  a)
{
    double sum2 =  f(a);
    return sum2;
}

double f(std::vector<double>   x) # if I put "& x" instead of x, it will generate and error (see below)
{
    // do something
    double sum = std::accumulate(x.begin(),x.end(),0.0);
    return sum;
}

int main()
{
    std::vector<double> x {1,2,3};
    std::cout << add(f, x) << std::endl;
    return 0;
}

错误:

 main.cpp: In function ‘int main()’:
main.cpp:23:26: error: invalid initialization of reference of type ‘const std::function<double(std::vector<double>)>&’ from expression of type ‘double (*)(std::vector<double>&)’
     std::cout << add(f, x) << std::endl;
                          ^
main.cpp:7:8: error: in passing argument 1 of ‘double add(const std::function<double(std::vector<double>)>&, std::vector<double>)’
 double add(const std::function<double(std::vector<double>)> &f, std::vector<double>  a)

0 个答案:

没有答案