【发布时间】:2014-05-26 22:53:12
【问题描述】:
我有以下一段代码,其中我声明了 2 个将函数作为参数的函数(一个使用 std::function,另一个使用指向函数的指针)。作为参数的函数必须具有原型std::complex<double>(const std::complex<double>&)。此类参数的一个示例是 C++11 中的 std::sqrt,请参阅 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<double> -
好的,我现在才发现这个 :) 无论如何,谢谢,这确实是问题。
-
@PeterT 不能保证
std::sqrt存在作为template函数,或者有一个函数,或者它的第一个template参数是它的参数的类型。 -
@Yakk 他正在使用这个函数en.cppreference.com/w/cpp/numeric/complex/sqrt 这是一个模板函数
-
@Yakk,至少他们在标准 C++11 中是这么说的,
std::sqrt是为复数模板化的。
标签: c++ c++11 function-pointers std-function