C++ Logo


Advanced search

Re: [std-proposals] Type-safe printf and auto

From: Zhihao Yuan <zy_at_[hidden]>
Date: Mon, 13 Mar 2023 05:11:38 +0000
On Sunday, March 12th, 2023 at 7:44 PM, Robin Rowe via Std-Proposals <std-proposals_at_[hidden]> wrote:


> unsigned i = 0;
> printf("%d",i);// Warning: use %u

> [...]

> I'm only suggesting that the compiler, when given "%?" in the first
> printf call above, be able to replace it silently with "%u". However, if
> the format isn't a string constant in the printf call, then the format
> string must be fully specified.

> In the error case that the printf interpreter receives a "%?" through
> this hole, the behavior could be to print a message such as "printf %?
> format error", as printf at runtime doesn't know what is packed in variargs.

Sound feasible. It could be done by introducing
a special form _Deduce_format_string("foo {} {}", a, b)
which expands to "foo %d %s", a, b like a C++ parameter
pack. Then this will allow us to create
printf-like macros in the library:

  #define fprintf_g(fmt, ...) fprintf(_Deduce_format_string(fmt, __VA_ARGS__), __VA_ARGS__))

Zhihao Yuan, ID lichray
The best way to predict the future is to invent it.

Received on 2023-03-13 05:11:47