c++ - 在表达式中使用用户定义的文字有时需要空格

标签 c++ c++11 user-defined-literals

以下代码在 GCC 和 Clang 中编译:

long double operator""_a(long double);     
auto x = 0e1_a+0; // OK 

但不是这个(将 _a 替换为 _e):

long double operator""_e(long double);
auto y = 0e1_e+0; // Error: unable to find numeric literal operator 'operator""_e+0'

OTOH,这段代码编译:

auto z = 0e1_e +0; // OK

这是怎么回事?

(本题灵感来自this GCC bug report。)

最佳答案

再次最大咀嚼罢工。

[lex.pptoken]/p3:

If the input stream has been parsed into preprocessing tokens up to a given character:

  • [two exceptions not relevant here]
  • Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail, except that a header-name (2.8) is only formed within a #include directive (16.2).

问题在于 0e1_e+00e1_a+0 不同,它是一个有效的预处理编号 ([lex.ppnumber]):

pp-number:
    digit
    . digit
    pp-number digit
    pp-number identifier-nondigit
    pp-number ’ digit
    pp-number ’ nondigit
    pp-number e sign
    pp-number E sign
    pp-number .

因此,0e1_e+0 被解析为单个 pp-number 预处理标记,然后由于无法转换为有效标记(例如显而易见的原因)。

另一方面,

0e1_a+0 被解析为三个标记,0e1_a+0,一切都很好。

关于c++ - 在表达式中使用用户定义的文字有时需要空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670238/

相关文章:

c++覆盖基类的功能

c++ - 如何使用枚举将 char 值映射到 int

c++ - 如何在Macro中用用户定义文字(UDL)组成字符串化?

C++ - 在构造函数中初始化指针数组

c++ - 如何编写写入/var/log/myapp 目录的 C/C++ 应用程序?

c++ - 是否可以向 C++ 用户定义的文字运算符传递空指针?

c++ - const cast 和 std launder

c++ - QObject 重入和线程安全

c++ - 在 C++ 中使用函数指针映射枚举键和值

使用 clang 3.5.0 和 libstdc++ 4.8.2 的 C++11 std::regex_replace 行为