带有inttype的枚举类的Printf不能在clang中工作

printf of enum classes with inttypes does not work with clang

本文关键字:clang 不能 工作 Printf inttype 枚举 带有      更新时间:2023-10-16

请考虑以下最小示例:

#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;
}

参见Live Example

这个例子可以很好地编译gcc,例如gcc 4.9.4。这个例子不能用clang编译,例如clang 3.9.0

为什么不可能通过使用相应的printf说明符来打印从std-inttypes派生的enum类,在这种情况下PRIu8在clang?这是一个clang编译器的bug吗?还是我错过了c++标准中的某个细节?

编译错误

warning: format specifies type 'unsigned int' but the argument has
underlying type 'uint8_t' (aka 'unsigned char') [-Wformat]

enum class Foo不是一个uint8_t,它是一个恰好使用uint8_t作为其底层表示的枚举。如果您想将其转换为uint8_t,请使用static_cast

类型系统实际上在这里试图帮助您-类型不同的(即使是可转换的)。