C ++相同名称空间问题

时间:2018-12-27 02:30:49

标签: c++

qqplotrstd中有<iostream>个命名空间。并且它具有相同的名为<cmath>的函数,依此类推。但是它与参数和返回类型不同。

这是代码。

sinh

我编译了它。

  

$ clang -c test.cpp

如下所示的编译器消息。

#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;
}

test.cpp:8:27: error: no matching constructor for initialization of 'std::vector<HyperbolicFn>' (aka 'vector<function<double (double)> >') std::vector<HyperbolicFn> fns = { ^ ~ 中,标头包含<cmath>函数。但是double sinh(double)<iostream>)没有。

我该如何解决?我想将此代码与<complex>标头中的函数一起使用。

1 个答案:

答案 0 :(得分:4)

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); }
};