在32位和64位程序中使用std :: chrono :: duration :: rep和printf

wul*_*jey 7 c++ io c++11 long-integer c++-chrono

有这个代码:

#include <cstdio>
#include <chrono>

int main()
{
  auto d = std::chrono::microseconds(1).count();
  printf("%lld", d);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当在64位模式下编译时,会出现警告:

main.cpp: In function ‘int main()’:
main.cpp:7:19: warning: format ‘%lld’ expects argument of type ‘long long int’, but argument 2 has type ‘long int’ [-Wformat=]
   printf("%lld", d);
                   ^
Run Code Online (Sandbox Code Playgroud)

在32位模式下编译时使用此警告(使用-m32标志).它看起来就像std::chrono::duration::rep是一个类型的long int在64位程序,并long long int在32位程序.

有没有一种可移植的方式来打印它像%zu说明符size_t

And*_*ing 9

至于你说的是,使用std::cout是不是你可以将值转换成所需的最小数据类型的选项1这是long long int2并使用相应的转换符:

printf("%lld", static_cast<long long int>(d));
Run Code Online (Sandbox Code Playgroud)

要避免显式转换,您还可以直接使用数据类型而不是auto说明符:

long long int d = std::chrono::microseconds(1).count();
printf("%lld", d);
Run Code Online (Sandbox Code Playgroud)

1对于所需的最小数据类型,我指的是可以表示两种实现中的值的最小类型.
2long long int类型必须是至少64位宽的,在这里看到的SO.


Clo*_*onk 5

不要使用auto限定符,而是使用固定大小的整数 int64_t。

#include <cstdio>
#include <chrono>
#include <cinttypes>

int main()
{
    int64_t d = std::chrono::microseconds(1).count();
    printf("%" PRId64 "\n", d);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)