c++ - 来自类型 <未解析的重载函数类型> 的无效 static_cast

标签 c++ function-pointers static-cast

我编写了以下函数来对 vector 的每个元素应用各种数学运算:

namespace MYFUNCTION
{
    template<class T>
    std::vector<T> eop(const std::vector<T> &v1, T (*f)(T))
    {
        std::vector<T> v2(v1.size());
        for(int ii = 0; ii < v1.size(); ii++)
        {
            v2[ii] = (*f)(v1[ii]);
        }
        return v2;
    }
}

我还重载了 cosh() std::vector 的函数参数:

namespace MYFUNCTION
{
    template<class T>
    std::vector<T> cosh(const std::vector<T> v1)
    {
        return eop(v1,static_cast<T (*)(T)>(&std::cosh));
    }
}

如果我将此函数用于类型 double一切安好。如果我使用 std::complex<double>相反,我得到一个编译器错误。

std::vector<double> a(2);
a[0] = 1.0;
a[1] = 2.0;
std::cout << MYFUNCTION::cosh(a) << std::endl; // Works fine.

std::vector<std::complex<double> > b(2);
b[0] = 1.0 + std::complex<double>(0.0,1.0);
b[1] = 2.0;
std::cout << MYFUNCTION::cosh(b) << std::endl; // Compiler error.

编译错误是:

error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘std::complex<double> (*)(std::complex<double>)’

编辑: 这是什么 cosh函数看起来像 complex.h :

template<class T> complex<T> cosh (const complex<T>& x);

这是什么cosh函数看起来像 cmath.h :

double cosh (double x);

我已经包括了 complex.hcmath.h .

最佳答案

std::cosh对于 std::complex<T>是一个函数模板,&std::cosh对编译器没有意义,因为 std::cosh 不是函数,它是函数族的模板。您需要编写另一个重载来处理这种情况:

#include <complex> //it is where std::cosh<T> is defined

template<class T>
std::vector<std::complex<T>> cosh(std::vector<std::complex<T>> const & v1)
{
    typedef std::complex<T> cosh_type( std::complex<T> const &);
    return eop(v1, static_cast<cosh_type*>(&std::cosh<T>) );
}

顺便说一句,通过引用传递参数以避免不必要的复制。

希望对您有所帮助。

关于c++ - 来自类型 <未解析的重载函数类型> 的无效 static_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281151/

相关文章:

c++ - 如何在手动编码时以直接的方式检测模板函数的适当返回类型

C++ 舍入问题

c++ - 如何获得两个(p1,p2)之间的 vector 方向?

在C中调用函数指针时出现编译错误

c - C中主下标值错误

当两个线程读取文件并标记 CSV 文件时,c++ Boost 多线程运行缓慢

c++ - 指向成员函数语法的奇怪指针

c++ - static_cast 到右值引用和 std::move 在初始化中更改它们的参数

c++ - 编译错误 : "no matching function for call to" when returning static_cast reference

c++ - 重载 C++ 引用类型转换(向下转换继承)