Convert complex<int16_t> to complex<double>

走远了吗. 提交于 2019-12-13 01:35:19

问题


Is there anyway in C++11 to do this:

 std::complex<int16_t> integer(42,42);
 std::complex<double> doub(25.5,25.5);
 std::complex<double> answer = integer*doub;

The error is

error: no match for ‘operator*’ (operand types are    
‘std::complex<short     int>’ and ‘std::complex<double>’)
std::complex<double> answer = integer*doub;

I have tried static_cast like;

std::complex<double> answer = static_cast<std::complex<double>>(integer)*doub;

回答1:


There's no predefined convertion from complex<double> to complex<int16_t> or viceversa.

You can define your own:

template <typename D, typename S> std::complex<D> cast(const std::complex<S> s)
{
    return std::complex<D>(s.real(), s.imag());
}

int main()
{
    std::complex<int16_t> integer(42, 42);
    std::complex<double> doub(25.5, 25.5);
    std::complex<double> answer = cast<double, int16_t>(integer)*doub;
}


来源:https://stackoverflow.com/questions/34219555/convert-complexint16-t-to-complexdouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!