将std::complex<double>强制转换为__complex128

7

我正在尝试在GCC中使用quadmath库。我有一个复双精度值,希望将其强制转换为相应的四倍精度复数__complex128。以下是一个最小(非)工作示例:

#include <quadmath.h>
#include <complex>
#include <stdio.h>
using namespace std::complex_literals;

int main(){
   std::complex<double> x = 1 + 2i;
   std::printf("x = %5.5g + %5.5g\n", x.real(), x.imag()); 
   __complex128 y = 2+2i;
   y = x;
  return 0;
}

当我尝试使用以下编译此代码时

 g++ test.cpp -lquadmath -o test

I get the following error:

test.cpp:10:6: error: cannot convert 'std::complex<double>' to '__complex128 {aka __complex__ __float128}' in assignment
y = x;

如果我尝试使用显式类型转换替换赋值行,
y = (__complex128) x;

我遇到了类似的错误。
test.cpp:10:21: error: invalid cast from type 'std::complex<double>' to type '__complex128 {aka __complex__ __float128}'
y = (__complex128) x;

如何在这两种类型之间进行转换?
2个回答

3

我猜你正在使用GCC编译器,如果是这样,你可以使用__real____imag__扩展来设置你的__complex128的各个分量:

__complex128 y;
__real__ y = x.real();
__imag__ y = x.imag();

这也适用于Clang的__complex64,(Clang还不支持__complex128)。

谢谢!那解决了问题。我不知道__real__和__imag__扩展。真巧妙。 - Jeff

0

我必须假设这里存在某种类型兼容性问题,因为据我所知 __complex__ 相当古老(参见 https://gcc.gnu.org/onlinedocs/gcc/Complex.html)。作为解决这个问题的一种方法,您可以尝试:

y = 1.0i;
y *= x.imag();
y += x.real();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接