我发现下面的代码在 gcc 4.7.3 上有编译错误,但在 clang 3.3 上没有:
#include <cstdint>
struct X {
explicit operator uint32_t() { return 0; }
};
int main() {
static_cast< int >( X() );
return 0;
}
问题是,哪个是对的? Gcc 4.7.3 说:
testcast.cpp:8:29: error: invalid static_cast from type 'X' to type 'int'
我认为发生的情况是 clang 使用 uint32_t 运算符获取无符号数,然后将其隐式转换为 int。我怀疑规范不会对此未定义,因此我预计其中一个编译器是错误的。
最佳答案
您必须将其显式转换为uint32_t
,否则会出现编译错误。你应该试试这个:
static_cast< uint32_t >( X() );
所以,如果它在 clang-3.3 中没有出错,它似乎是一个错误。
关于c++ - static_cast 和显式转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077027/