繁体   English   中英

来自类型的无效static_cast <unresolved overloaded function type>

[英]Invalid static_cast from type <unresolved overloaded function type>

我编写了以下函数,将各种数学运算应用于向量的每个元素:

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

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

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对编译器没有意义,因为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>) );
}

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

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM