将 std::complex<double> 类型转换为 __complex128

Typecasting std::complex<double> to __complex128

我正在尝试使用 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

我收到以下错误:

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;

这两种类型之间如何转换?

我猜您使用的是 GCC,在这种情况下,您可以使用 __real____imag__ 扩展来设置 __complex128:

的各个组件
__complex128 y;
__real__ y = x.real();
__imag__ y = x.imag();

这在 __complex64 的 Clang 中也有效(Clang 尚不支持 __complex128)。

我不得不假设这里存在某种类型兼容性问题,因为据我所知 __complex__ 非常古老(请参阅 https://gcc.gnu.org/onlinedocs/gcc/Complex.html)。作为解决此问题的一种方法,您可以尝试:

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