我编写了以下函数来对 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.h
和 cmath.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/