我最近一直在使用 Clang
,这种小小的好奇心总是在解析显式转换时出现。
为了明确我的观点,这里有一些基本代码:
int main(){
int my_int;
float my_float;
my_int = (int) my_float;
return 0;
}
当然,您会期望 my_int = (int) my_float;
被解析为 CStyleCastExpr ,带有 CastKind CK_FloatingToIntegral 的,但事实并非如此,事实上,强制转换的性质存储在 ImplicitCastExpr 中。而CStyleCastExpr
则具有NoOp
性质。
这是此代码的匹配 AST 转储:
|-DeclStmt 0x2eb3528 <line:3:1, col:11>
| `-VarDecl 0x2eb34d0 <col:1, col:5> my_int 'int'
|-DeclStmt 0x2eb35a8 <line:4:1, col:15>
| `-VarDecl 0x2eb3550 <col:1, col:7> my_float 'float'
|-BinaryOperator 0x2eb3678 <line:5:1, col:16> 'int' lvalue '='
| |-DeclRefExpr 0x2eb35c0 <col:1> 'int' lvalue Var 0x2eb34d0 'my_int' 'int'
| `-CStyleCastExpr 0x2eb3650 <col:10, col:16> 'int' <NoOp>
| `-ImplicitCastExpr 0x2eb3638 <col:16> 'int' <FloatingToIntegral>
| `-ImplicitCastExpr 0x2eb3620 <col:16> 'float' <LValueToRValue>
| `-DeclRefExpr 0x2eb35e8 <col:16> 'float' lvalue Var 0x2eb3550 'my_float' 'float'
`-ReturnStmt 0x2eb36c0 <line:6:1, col:8>
`-IntegerLiteral 0x2eb36a0 <col:8> 'int' 0
这似乎有点令人困惑,因为对我来说,ImplicitCastExpr 应该仅在发生某些意外转换时才被识别(请参阅下面的代码)。
int main(){
int my_int;
float my_float;
// implicit cast from float to int
my_int = my_float;
return 0;
}
您对此有何解释?
最佳答案
这似乎是 clang 实现的副作用:
http://comments.gmane.org/gmane.comp.compilers.clang.devel/17369
生成转换节点的源代码文件是:
https://github.com/llvm-mirror/clang/blob/master/lib/Sema/SemaCast.cpp
关于c++ - 为什么 Clang 将显式强制转换解释为隐式强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119370/