c++ - 使用用户定义的文字有条件地包含在 C++11 中?

标签 c++ c++11

在 C++11 中,当预处理指令形式为...

#if expr

...遇到,expr被评估为 constant-expression16.1 [cpp.cond] 中所述.

这是在 expr 上的宏替换之后完成的,它的标识符(和关键字)被 0 替换,它的 preprocessing-tokens转换为 tokens , defined运算符被评估,等等。

我的问题是当 expr 中的一个标记时会发生什么是 user-defined-literal

用户定义字面量类似于函数调用,但函数调用不能出现在expr中(我认为),作为标识符替换的副作用。然而技术上user-defined-literals能活下来。

我怀疑这是一个错误,但我不太明白如何从标准中得出结论?

也许是在第 16 条上添加用户定义文字的(迂腐的)影响 [cpp]只是被忽略了?

还是我遗漏了什么?

更新:

举例说明:

这个预处理的目的是什么:

#if 123_foo + 5.5 > 100
bar
#else
baz
#endif

bar 或 baz 还是错误?

GCC 4.7 报告:

test.cpp:1:5: error: user-defined literal in preprocessor expression

所以它认为这是一个错误。这可以引用标准来证明吗?或者这只是“隐式”?

最佳答案

In C++11 when a preprocessing directive of the form... #if expr ...is encountered, expr is evaluated as a constant-expression as described in 16.1 [cpp.cond].

This is done after macro replacement on expr, its identifiers (and keywords) are replaced by 0, its preprocessing-tokens are converted to tokens, defined operator is evaluated, and so on.

My question is what happens when one of the tokens in expr is a user-defined-literal?

程序格式错误。

我的论点的核心来自于 16.1/1 脚注 147 中的观察,即在翻译阶段 4 中没有标识符除了宏名称。

参数:

根据 2.14.8 [lex.ext]/2

A user-defined-literal is treated as a call to a literal operator or literal operator template (13.5.8).

因此,即使在 16.1/4 中描述的所有替换之后,我们仍有对(运算符)函数的剩余调用。 (其他尝试,例如使用 constexpr 函数,将因将所有非宏 identifiers 替换为 0 而受阻。)

因为这发生在翻译阶段 4,所以还没有定义甚至声明函数;尝试查找 literal-operator-id 一定会失败(有关类似的论点,请参阅 16.1/1 中的脚注 147)。

从稍微不同的角度来看,5.19/2我们发现:

A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression (3.2) [...]:

  • [...]
  • an invocation of a function other than a constexpr constructor for a literal class or a constexpr function;
  • an invocation of an undefined constexpr function or an undefined constexpr constructor [...];

据此,在常量表达式中使用用户定义的文字需要definedconstexpr literal operator,在翻译阶段 4 中同样无法使用。

gcc 拒绝这个是对的。

关于c++ - 使用用户定义的文字有条件地包含在 C++11 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915238/

相关文章:

c++ - Clang 输出错误 "no matching construct for initialization"

c++ - 覆盖所有类型的 operator<<

c++ - 从调用的可调用目标将 std::function 设置为 nullptr

c++ - 在这种情况下是否存在内存泄漏?

c++ - QString::fromUtf8(str) 和\u编码的字符序列

c++ - 使用新运算符和指针的两个不同声明之间的区别

c++ - 将谓词传递给 QWaitCondition?

c++ - 为什么 EnumWindows 在服务中不工作?

c++ - cv::detail::MultiBandBlender 照片末尾出现奇怪的白色条纹

c++ - 全局函数和不明确的参数 NULL 与 char* 在 vs 2013 和 GCC 之间