jtb*_*des 13 c++ clang complex-numbers user-defined-literals c++11
当我在ideone.com上运行此代码时,它会打印(2,3):
#include <iostream>
#include <complex>
int main() {
std::complex<double> val = 2 + 3i;
std::cout << val << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是当我在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)
Run Code Online (Sandbox Code Playgroud)
想象中发生了什么?难道我做错了什么?
Jes*_*ood 10
我相信第一个例子,编译器使用GNU扩展:
-fext-numeric-literals (C++ and Objective-C++ only)
Run Code Online (Sandbox Code Playgroud)
接受虚构的,定点的或机器定义的文字数字后缀作为GNU扩展.关闭此选项后,这些后缀将被视为C++ 11用户定义的文字数字后缀.默认情况下,所有前C++ 11方言和所有GNU方言都启用:-std = c ++ 98,-std = gnu ++ 98,-std = gnu ++ 11,-std = gnu ++ 14 .默认情况下,此选项在ISO C++ 11之后关闭(-std = c ++ 11,...).
当我用clang运行它时,我得到(你正在使用-Wall -pedantic?:)):
警告:虚构常量是GNU扩展[-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;
}
Run Code Online (Sandbox Code Playgroud)
从文档:
这些运算符在名称空间std :: literals :: complex_literals中声明,其中literals和complex_literals都是内联名称空间.使用namespace std :: literals,使用namespace std :: complex_literals,并使用namespace std :: literals :: complex_literals,可以获得对这些运算符的访问.