1

Please consider following minimum example:

#include <cstdint>
#include <cstdio>
#include <cinttypes>
#include <type_traits>

enum class Foo : uint8_t
{
  John,
  Jane
};

int main()
{
  // does not compile with clang but works fine with gcc
  printf("here is my %" PRIu8 "\n", Foo::John);

  //with cast works fine also with clang
  using T = typename std::underlying_type<Foo>::type;
  printf("here is my %" PRIu8 "\n", T(Foo::John));

  //with cast works fine also with clang
  printf("here is my %" PRIu8 "\n", uint8_t(Foo::John));

  return 0;
}

see also Live Example

This example compiles well with gcc, e.g. gcc 4.9.4. This example does not compile with clang, e.g. clang 3.9.0

Why is it not possible to printf enum classes that are derived from std-inttypes by just using the corresponding printf specifier, in that case PRIu8 in clang? Is that a clang compiler bug? Or do I miss a detail in the C++ standard?

The compile error is

warning: format specifies type 'unsigned int' but the argument has
underlying type 'uint8_t' (aka 'unsigned char') [-Wformat]
3
  • Missed the -Werror flag, which we are using in our code bases. But I'm still curious, what clang's problem is Commented Oct 19, 2016 at 13:24
  • but it is still an uint8_t isn't it? And the correct format specifier is ´PRIu8´ isn't it? So whats wrong? Commented Oct 19, 2016 at 13:32
  • No, it is not a uint8_t it is a enum class Foo. As far as the type system is concerned those are different things (which is a good thing). Commented Oct 19, 2016 at 15:36

1 Answer 1

2

enum class Foo is not a uint8_t it is an enumeration that just happens to use uint8_t as its underlying representation. If you want it to be converted to uint8_t, use a static_cast.

The type system is actually trying to help you here - the types are different (even if convertible).

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

Comments

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.