C++ 来自类型的无效静态\u转换<;未解析的重载函数类型>;
我编写了以下函数,将各种数学运算应用于向量的每个元素:C++ 来自类型的无效静态\u转换<;未解析的重载函数类型>;,c++,function-pointers,static-cast,C++,Function Pointers,Static Cast,我编写了以下函数,将各种数学运算应用于向量的每个元素: 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
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;
}
}
如果我对typedouble
使用此函数,一切都很好。如果使用std::complex
,则会出现编译器错误
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.
这就是cmath.h
中的cosh
函数的外观:
template<class T> complex<T> cosh (const complex<T>& x);
double cosh (double x);
由于
std::cosh
的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>) );
}
#include//它是定义std::cosh的地方
模板
标准::矢量余弦(标准::矢量常数和v1)
{
typedef std::complex cosh_type(std::complex const&);
返回eop(v1,静态_-cast(&std::cosh));
}
顺便说一下,通过引用传递参数以避免不必要的副本
希望能有帮助。@leemes:那是个打字错误。
double cosh (double x);
#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>) );
}