C++相同的命名空间问题

C++ same namespace issue

本文关键字:命名空间 问题 C++      更新时间:2023-10-16

<iostream><cmath>中有std命名空间。它具有相同的功能,名为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 测试.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>标头包含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); }
};