gpt4 book ai didi

c++ - 将 std::function 与函数指针作为参数传递时出错

转载 作者:行者123 更新时间:2023-11-28 00:28:33 24 4
gpt4 key购买 nike

我有以下一段代码,其中我声明了 2 个将函数作为参数的函数(一个使用 std::function ,另一个使用指向函数的指针)。作为参数的函数必须具有原型(prototype) std::complex<double>(const std::complex<double>& ).此类参数的一个示例是 std::sqrt在 C++11 中,参见 http://en.cppreference.com/w/cpp/numeric/complex/sqrt .现在,我完全不知道为什么采用指向函数指针的函数有效(即 g_of_ten ),而另一个采用 std::function 的函数作为参数,没有(即 f_of_ten )。如果我取消注释该行

//cout << f_of_ten(std::sqrt) << endl; // ERROR here!!!

我得到了错误

 error: no matching function for call to 'f_of_ten'
cout << f_of_ten(std::sqrt) << endl; // ERROR here!!!
^~~~~~~~
/Users/vlad/minimal.cpp:10:6: note: candidate function not viable: no overload of 'sqrt' matching 'std::function<cplx (const cplx &)> &' for 1st argument
cplx f_of_ten(std::function<cplx(const cplx &)>& x)
^
1 error generated.

我完全不明白为什么会这样,虽然我认为 std::function实际上是各种仿函数(包括标准函数)的包装器。任何帮助都非常受欢迎!下面是代码:

#include <cmath>
#include <complex>
#include <functional>
#include <iostream>

using namespace std;

using cplx = complex<double>; // to save some typing

cplx f_of_ten(std::function<cplx(const cplx &)> x) // the problematic one
{
return x(10);
}

cplx g_of_ten(cplx(*x)(const cplx &)) // this works
{
return (*x)(10);
}


int main()
{
//cout << f_of_ten(std::sqrt) << endl; // compile ERROR here!!!
cout << g_of_ten(std::sqrt) << endl;
}

PS:我当然也试过了cout << f_of_ten(&std::sqrt) << endl; ,同样的故事,编译时错误。

@Yakk,

这很好用:

#include <cmath>
#include <complex>
#include <functional>
#include <iostream>
#include <valarray>

using cplx = std::complex<double>; // to save some typing

cplx f_of_ten(std::function<cplx(const cplx &)> x) // the problematic one
{
return x(10);
}

cplx g_of_ten(cplx(*x)(const cplx &)) // this works
{
return (*x)(10);
}


int main()
{
//cout << f_of_ten(std::sqrt<double>) << endl; // compile ERROR here!!!
std::cout << g_of_ten(std::sqrt) << std::endl;
}

最佳答案

std::sqrt 的重载不止一个,您的代码不知道如何确定您想要哪一个。

尝试:

typedef cplx(*complex_function)(const cplx &);

std::cout << f_of_ten( complex_function( std::sqrt ) ) << std::endl;

关于c++ - 将 std::function 与函数指针作为参数传递时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23878679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com