Home > database >  How to pass a pointer argument to std::format?
How to pass a pointer argument to std::format?

Time:11-16

In the following code, when the first argument is an int and another a pointer casted to void*, the code compiles:

AYAPI_API int AYBlitBuffer(int a1, int a2, int* a3, int* a4)
{
    Log(std::format("@{}: a1 = {}, a2 = {}, a3 = {}, a4 = {}", __FUNCTION__, a1, a2, static_cast<void*>(a3), static_cast<void*>(a4)));
    return 0;
}

If, however, passing a unique argument that is a pointer, the code does not compile:

AYAPI_API int AYRenderPrim(int *a1)
{
    Log(std::format("@{}: a1 = {:#010x}", __FUNCTION__, static_cast<void*>(a1)));
    return 0;
}

The actual error:

error C7595: 'std::_Basic_format_string<char,const char (&)[13],void *>::_Basic_format_string': call to immediate function is not a constant expression

How can one pass both integers and pointers to integers to be formatted by std::format?

CodePudding user response:

The error you are seeing has nothing to do with the presence or absence of any int arguments amongst the parameters to the call to std::format. (Try changing the format string in your first snippet so that it ends with a4 = {:#010x} in place of a4 = {} and you will see the same error message, there.)

Rather, the error – albeit cryptic – occurs because the format specifier you provide is not valid for a pointer argument. The # specifer is only valid for integer or floating-point arguments (as also the leading 0 and the trailing x?). (Possibly useful cppreference page.)

So, in your case, if you want to specify such a format for a pointer value, you should cast that pointer to a suitable integer type (intptr_t or uintptr_t are likely good candidates) rather than to a void*:

AYAPI_API int AYRenderPrim(int* a1)
{
    Log(std::format("@{}: a1 = {:#010x}", __FUNCTION__, reinterpret_cast<intptr_t>(a1)));
    return 0;
}
  • Related