void.pointer
void.pointer

Reputation: 26365

How to cast pointer value to enumeration?

I have the following:

enum TestEnum { One=1, Two, Three };

int main()
{
    char const* data = reinterpret_cast<char const*>(One);

    TestEnum e = reinterpret_cast<TestEnum>(data);
}

Clang fails to compile this:

main.cpp:11:18: error: reinterpret_cast from 'const char *' to 'TestEnum' is not allowed
    TestEnum e = reinterpret_cast<TestEnum>(data);
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Why won't reinterpret_cast work in this situation? I've tried removing const but that doesn't make a difference. I didn't see anything in the C++11 specification that states special behavior for enumerations.

Upvotes: 2

Views: 528

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477100

From 5.2.10/4: "A pointer can be explicitly converted to any integral type large enough to hold it." Enums are not integral types.

(The reverse direction is allowed by paragraph 5: "A value of integral type or enumeration type can be explicitly converted to a pointer.")

Upvotes: 3

Related Questions