c – 设置std :: function变量以引用std :: sin函数

前端之家收集整理的这篇文章主要介绍了c – 设置std :: function变量以引用std :: sin函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个关于如何正确使用新的C 11 std :: function变量的问题.我已经看过几个搜索互联网的例子,但它们似乎并没有涵盖我正在考虑的用例.以这个最小的例子为例,其中函数fdiff是在numeric.hxx中定义的有限前向差分算法的实现(这不是问题,我只是想给出一个上下文的原因,为什么我想要任意函数和传递它).
  1. #include <functional>
  2. #include <iostream>
  3. #include <cmath>
  4. #include "numerical.hxx"
  5.  
  6. int main()
  7. {
  8. double start = 0.785398163;
  9. double step = 0.1;
  10. int order = 2;
  11.  
  12. std::function<double(double)> f_sin = std::sin;
  13.  
  14. std::cout << fdiff(start,step,order,f_sin) << std::endl;
  15.  
  16. return 0;
  17. }

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

  1. test.cpp:11:32: error: no viable conversion from '<overloaded function type>' to
  2. 'std::function<double (double)>'
  3. std::function<double(double)> f_sin = std::sin;
  4. ^ ~~~~~~~~
  5. /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2048:7: note:
  6. candidate constructor not viable: no overload of 'sin' matching
  7. 'nullptr_t' for 1st argument
  8. function(nullptr_t) noexcept
  9. ^
  10. /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2059:7: note:
  11. candidate constructor not viable: no overload of 'sin' matching 'const
  12. std::function<double (double)> &' for 1st argument
  13. function(const function& __x);
  14. ^
  15. /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2068:7: note:
  16. candidate constructor not viable: no overload of 'sin' matching
  17. 'std::function<double (double)> &&' for 1st argument
  18. function(function&& __x) : _Function_base()
  19. ^
  20. /usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2092:2: note:
  21. candidate template ignored: couldn't infer template argument '_Functor'
  22. function(_Functor __f,^
  23. 1 error generated.

或者来自g

  1. test.cpp: In function int main()’:
  2. test.cpp:11:45: error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type std::function<double(double)>’ requested

据我所知,这是因为std :: sin是作为标准库中的模板类实现的,但我似乎无法弄清楚我需要做些什么来提供足够的特化来获取函数引用.我也尝试了各种各样的东西,比如使用new auto关键字,使用& std :: sin来获取指针等,但它们都给了我相同类型的错误.

解决方法

std::sin是一个重载函数:你必须消除你所指的std :: sin重载的歧义:
  1. std::function<double(double)> f_sin = (double(*)(double))&std::sin;

在某些情况下,编译器可以消除重载函数的歧义(例如,如果f_sin的类型为double(*)(double),则不需要强制转换).但是,这不是其中之一.

猜你在找的C&C++相关文章