I am using std::atomic<unsigned int>
in my program. How can I print its value using printf
? It doesn't work if I just use %u
. I know I can use std::cout
, but my program is littered with printf
calls and I don't want to replace each of them. Previously I was using unsigned int
instead of std::atomic<unsigned int>
, so I was just using %u
in the format string in my printf
call, and therefore printing worked just fine.
The error I'm getting when trying to print the std::atomic<unsigned int>
now in place of the regular unsigned int
is:
error: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘std::at开发者_如何学Pythonomic<unsigned int>’ [-Werror=format=]
another option, you can use the atomic variable's load()
method. E.g.:
std::atomic<unsigned int> a = { 42 };
printf("%u\n", a.load());
template<typename BaseType>
struct atomic
{
operator BaseType () const volatile;
}
Use a typecast to pull out the underlying value.
printf("%u", unsigned(atomic_uint));
精彩评论