Clean code to printf size_t in C++ (or: Nearest equivalent of C99's %z in C++)

前端 未结 9 2597
醉梦人生
醉梦人生 2020-12-07 14:20

I have some C++ code that prints a size_t:

size_t a;
printf(\"%lu\", a);

I\'d like this to compile without warnings on both 32

9条回答
  •  清歌不尽
    2020-12-07 14:56

    here's a possible solution, but it's not quite a pretty one..

    template< class T >
    struct GetPrintfID
    {
      static const char* id;
    };
    
    template< class T >
    const char* GetPrintfID< T >::id = "%u";
    
    
    template<>
    struct GetPrintfID< unsigned long long > //or whatever the 64bit unsigned is called..
    {
      static const char* id;
    };
    
    const char* GetPrintfID< unsigned long long >::id = "%lu";
    
    //should be repeated for any type size_t can ever have
    
    
    printf( GetPrintfID< size_t >::id, sizeof( x ) );
    

提交回复
热议问题