2016-10-19 19 views
1

では動作しません最低限の例を以下の点を考慮してください:printf関数は打ち鳴らす

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

この例では、例えば、gccでうまくコンパイルもLive Example

を見ますgcc 4.9.4。 この例はclangでコンパイルされません。 clang 3.9.0

std-inttypesから派生したenumクラスを対応するprintf指定子を使用してprintfできないのはなぜですか?その場合はclangのPRIu8?それはclangコンパイラのバグですか?または、C++標準の詳細を見逃していますか?

コンパイルエラーが

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

コードベースで使用している-Werrorフラグがありませんでした。しかし、私はまだ興味がありますが、clangの問題は – meddle0106

+0

ですが、それはまだuint8_tですか?正しいフォーマット指定子は'PRIu8 'ですか?だから何が間違っている? – meddle0106

+0

いいえ、それは 'uint8_t'ではありません。*' enum class Foo'です。タイプシステムが関係している限り、それらは異なるものです(これは良いものです)。 –

答えて

2

enum class Fooであるが、それだけでその基礎となる表現としてuint8_tを使用することが起こる列挙ですuint8_tではありません。 uint8_tに変換する場合は、static_castを使用してください。

タイプシステムは実際にあなたをここで助けようとしています - タイプはです(コンバーチブルであっても)。

関連する問題