Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_cast and explicit conversion operators

Tags:

c++

gcc

c++11

clang

I have found that the following code gives a compile error on gcc 4.7.3 but not on clang 3.3:

#include <cstdint>                                          

struct X {
    explicit operator uint32_t() { return 0; }
};

int main() {
    static_cast< int >( X() );
    return 0;
}

The question is, which is right? Gcc 4.7.3 says:

testcast.cpp:8:29: error: invalid static_cast from type 'X' to type 'int'

What I think happens is that clang uses the uint32_t operator to get an unsigned and then implicitly converts that to int. I suspect the spec does not leave this undefined, and as such I'd expect one of the compilers to be wrong.

like image 608
mornfall Avatar asked Jul 12 '26 23:07

mornfall


1 Answers

You must explicitly cast it to uint32_t, otherwise a compile error. You should try this:

static_cast< uint32_t >( X() );

So, If it doesn't make error in clang-3.3, it seems as a bug.

Observation: GCC and Clang-3.4 both reject the code and make compile errors.

like image 154
masoud Avatar answered Jul 15 '26 13:07

masoud