有std
<iostream>
中的命名空间和 <cmath>
.它具有相同的功能,名为 sinh
, 等。但它与参数和返回类型不同。
这是代码。
#include <iostream>
#include <cmath>
#include <functional>
#include <vector>
typedef std::function<double(double)> HyperbolicFn;
std::vector<HyperbolicFn> fns = {
std::sinh, std::cosh, std::tanh
};
auto main(void) -> int {
return 0;
}
我编译了它。
$ clang -c test.cpp
编译器信息如下。
test.cpp:8:27: error: no matching constructor for initialization of 'std::vector<HyperbolicFn>'
(aka 'vector<function<double (double)> >')
std::vector<HyperbolicFn> fns = {
^ ~
在<cmath>
header 包括 double sinh(double)
功能。但是<iostream>
( <complex>
) 没有。
我该如何解决这个问题?我想将此代码与 <cmath>
中的函数一起使用标题。
最佳答案
std::sinh
和其他函数被重载,而 std::function
不能很好地处理重载,它无法区分它们。您可以进行显式转换
using Hyper = double(*)(double);
std::vector<HyperbolicFn> fns = {
static_cast<Hyper>(std::sinh),
static_cast<Hyper>(std::cosh),
static_cast<Hyper>(std::tanh)
};
或者改用lambda
std::vector<HyperbolicFn> fns = {
[](double a) { return std::sinh(a); },
[](double a) { return std::cosh(a); },
[](double a) { return std::tanh(a); }
};
关于C++ 相同命名空间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53939121/