c++ - 设置一个 std::function 变量来引用 std::sin 函数

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

我有一个关于如何正确使用新的 C++11 std::function 变量的问题。我在网上搜索过几个例子,但它们似乎没有涵盖我正在考虑的用例。以这个最小的例子为例,其中函数 fdiffnumerical.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;
}

尝试编译上述程序时出现错误(在 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 1st argument
      function(nullptr_t) noexcept
      ^
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2059:7: note: 
      candidate constructor not viable: no overload of 'sin' matching 'const
      std::function<double (double)> &' for 1st argument
      function(const function& __x);
      ^
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2068:7: note: 
      candidate constructor not viable: no overload of 'sin' matching
      'std::function<double (double)> &&' for 1st argument
      function(function&& __x) : _Function_base()
      ^
/usr/lib/gcc/x86_64-unknown-linux-gnu/4.7.1/../../../../include/c++/4.7.1/functional:2092:2: note: 
      candidate template ignored: couldn't infer template argument '_Functor'
        function(_Functor __f,
        ^
1 error generated.

或者来自 g++

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

据我了解这个问题,这是因为 std::sin 是作为标准库中的模板类实现的,但我似乎无法弄清楚我需要做什么才能提供足够的特化以获得功能引用。我还尝试了各种方法,例如使用新的 auto 关键字,使用 &std::sin 获取指针等,但它们都给我相同类型的错误。

最佳答案

std::sin是一个重载函数:您必须消除您指的是哪个 std::sin 重载的歧义:

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

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

关于c++ - 设置一个 std::function 变量来引用 std::sin 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12500411/

相关文章:

c++ - 为什么我的 const ref 无效?

c++ - 在非 constexpr 函数上添加的 constexpr 限定符不会触发任何警告

php - 可以在运行时在 php 中将函数分配给类变量吗?

c++ - AspectC++ 入门

c++ - 包含自身列表的类

c++ - Purify 在使用 std::list::remove() 时揭示了潜在的空闲内存读取

c++ - 引用禁用复制构造函数/赋值的对象

c++ - 为什么 GCC 允许通过右值引用捕获?

c++ - 这里的typedef有什么用?

c# - 在 c# dll 中调用 delphi5 过程