2016-10-19 76 views
1

请考虑以下最低例如:printf的枚举类与inttypes并不铿锵工作

#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编译,例如铛3.9.0

为什么不能给printf是由STD-inttypes只要使用相应的printf说明符派生类的枚举,在这种情况下PRIu8在铛?这是一个铿锵编译器错误?或者我错过了C++标准中的细节?

编译错误是

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

错过了我们在代码库中使用的-Werror标志。但我仍然好奇,铿锵的问题是 – meddle0106

+0

,但它仍然是一个uint8_t不是吗?而正确的格式说明符是'PRIu8'不是吗?那么最新错误? – meddle0106

+0

不,它不是'uint8_t',它是'enum class Foo'。就类型系统而言,这些是不同的事情(这是一件好事)。 –

回答

2

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

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