小编jme*_*ert的帖子

设置std :: function变量来引用std :: sin函数

我有一个关于如何正确使用新的C++ 11 std::function变量的问题.我已经看过几个搜索互联网的例子,但它们似乎并没有涵盖我正在考虑的用例.拿这个最小的例子,其中函数fdiff是定义的有限前向差分算法的实现numerical.hxx(这不是问题,我只是想给出一个上下文的原因,为什么我想要采用任意函数并传递它) .

#include <functional>
#include <iostream>
#include <cmath>
#include "numerical.hxx"

int main()
{
    double start = 0.785398163;
    double step  = 0.1;
    int    order = 2;

    std::function<double(double)> f_sin = std::sin;

    std::cout << fdiff(start, step, order, f_sin) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

试图编译上面的程序给我错误(在clang ++中)

test.cpp:11:32: error: no viable conversion from '<overloaded function type>' to
      'std::function<double (double)>'
        std::function<double(double)> f_sin = std::sin;
                                      ^       ~~~~~~~~
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2048:7: note: 
      candidate constructor not viable: no overload of 'sin' matching
      'nullptr_t' for …
Run Code Online (Sandbox Code Playgroud)

c++ function-pointers std c++-standard-library c++11

7
推荐指数
1
解决办法
3213
查看次数