-
typename 的用法
2021-11-21 08:55 -
一个 7 行 C 代码的运行分析
2021-11-13 17:31这锅编译器可不背,在C语言标准草案n2596(我常用的草案,我猜测应该几乎每一版标准都有)中6.5第5条中就明确指出“If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.”。这属于未定义行为,基本上编译器怎么实现都行,特别是涉及到优化的时候。(但是无符号整数是“特例”(其实就是不算溢出),在6.2.5中第9条"The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.44) A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.")
比如说常见错误
(++a) = f(++a, ++a)
,这玩意应该是熟知的未定义行为,就不能期望某个特定的结果,和这个问题程序差不多。比如做优化的时候
if(a > 0 && b > 0){ if(a + b > 0){ // anything ... } else { // it is valid for this branch to be optimized out. } }
编译器有理由但不一定会优化掉第二个分支。
(补充,C++20标准中对于文章中举的例子已经不需要typename了,但是目前不同编译器支持情况还不同。
C++20之前依然需要typename。