c++ - static_cast 和显式转换运算符

标签 c++ gcc c++11 clang

我发现下面的代码在 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 中没有出错,它似乎是一个错误。

观察:GCCClang-3.4都拒绝代码并产生编译错误。

关于c++ - static_cast 和显式转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077027/

相关文章:

c - 使用 NetBeans 的 Linux 静态库中缺少符号

c++ - 使用 make_shared 初始化 const 成员

c++ - 我可以使用模板别名作为模板模板参数吗?

c++ - 实现 C++14 make_integer_sequence

c++ - 如何使用 C++ 观看 winapi dll 函数调用

c - 如何找到不相关的未使用属性?

c++ - Ubuntu 10.04 需要什么包才能运行用 gcc/g++ 4.7 编译的程序?

c++ - 为什么 vector 被视为按值传递,即使它是通过 const 引用传递的?

c++ - 滚动菜单在 C++ 中不起作用

c++ - cuda浮点精度