为什么复数文字在 clang 中不起作用?

Why don't complex-number literals work in clang?

当我运行这个代码on ideone.com时,它打印(2,3):

#include <iostream>
#include <complex>

int main() {
    std::complex<double> val = 2 + 3i;
    std::cout << val << std::endl;
    return 0;
}

但是当我在 macOS 10.11.6 上使用 clang 时,我没有收到任何错误或警告,但输出是 (2,0):

$ clang --version
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0

$ clang -lc++ test.cpp && ./a.out
(2,0)

虚部怎么了?我做错了什么吗?

我相信对于第一个示例,编译器使用的是 GNU 扩展:

-fext-numeric-literals (C++ and Objective-C++ only)

Accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off these suffixes are treated as C++11 user-defined literal numeric suffixes. This is on by default for all pre-C++11 dialects and all GNU dialects: -std=c++98, -std=gnu++98, -std=gnu++11, -std=gnu++14. This option is off by default for ISO C++11 onwards (-std=c++11, ...).

当我用 clang 运行 它时,我得到了(你在使用 -Wall -pedantic 吗?:)):

warning: imaginary constants are a GNU extension [-Wgnu-imaginary-constant]

无论哪种方式,您的代码都不符合标准。要使用 C++14 文字,请编写代码:

#include <iostream>
#include <complex>
using namespace std::complex_literals;
int main() {
    std::complex<double> val = 2.0 + 3i;
    std::cout << val << std::endl;
    return 0;
}

来自documentation

These operators are declared in the namespace std::literals::complex_literals, where both literals and complex_literals are inline namespaces. Access to these operators can be gained with using namespace std::literals, using namespace std::complex_literals, and using namespace std::literals::complex_literals.