C++ 相同命名空间问题

标签 c++

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/

相关文章:

c++ - 为 Visual Studio 安装 openCV 2.4 for C/C++

c++ - unique_ptr 与 vector : error: call to implicitly-deleted copy constructor of XXX

c++ - 在c++中显示小数点后两位

C++ 隐藏模板参数

c++ - cout 和 printf 中打印零的区别

c++ - 两个值之间的随机数

c++ - 使用 C++ Boost.Test 组织单元测试?

c++ - 用于增强 C++ 项目的 Delphi DLL

c++ - 使用 winapi 获取本地 IP 地址列表

c++ - 需要帮助以避免沮丧