3

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.

5
  • AFAIK, you'd still need to explicitly cast to uint32_t. Commented Nov 19, 2013 at 16:39
  • In this case, I think GCC is right in rejecting this code. Chained-conversion is not allowed: means, if A can convert into B which can convert into C, it does NOT mean A can directly convert into C. Commented Nov 19, 2013 at 16:47
  • @chris, yes that will work on both, but that's not quite what I'm asking -- this happens inside a relatively deep stack of templates, and clang will call a different function from gcc because it has a different idea of what is a valid expression. I like the gcc behaviour more in this case I guess, as I don't want the unsigned->signed conversion to happen "behind my back" (the conversions are explicit for a reason). But I'd rather know for sure which is right. :-) Commented Nov 19, 2013 at 16:54
  • @mornfall, I'm implying that GCC is correct, but I'm not completely sure. If Clang 3.4 rejects it, too, that's almost certainly the correct behaviour. Commented Nov 19, 2013 at 17:00
  • 4
    Tip-of-trunk clang rejects this with a very similar error message. Commented Nov 19, 2013 at 17:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The links you provided show a failure in both, but completely unrelated to my question (gcc is running in C++98 mode failing to even recognize the "explicit" keyword; clang says main.cpp:8:23: error: unknown type name 'uint32_t')
See here -- I don't know what version of clang that web runs, but it compiles the code without complaint if you actually tell it that it is C++11. (edit: it says clang version 3.4 (trunk 184460); hence even clang 3.4 claims the code is OK)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.