Is constexpr "[v [n]] sprintf possible?

My intuitive answer is yes, and the implementation can also be used by "printf". And it can be easy to overload custom types.

Has anyone ever tried to do this before?

+4
source share
2 answers

I believe that you cannot - the main problem is how you get the result from the function. When you return a string, you can actually return (1) a new -ed buffer (or malloc ed, which is just as bad), (2) a static buffer, or (3) fill some other buffer.

(1) expressly not permitted

(2) contrary to the sprintf contract (i.e. not constexpr sprintf should not do this either)

(3) appointment is not possible in constexpr .

If you just need "something like sprintf ", regardless of the possible inconvenient use, something like that. with such an interface will work:

 my_sprintf<my_string<'%', 'd', '%', 'c'>, my_data<int, 42>, my_data<char, 'l'> >::string_value 

Secondly, you could avoid the actual calculation of the string and just save the parameters of the sprintf call for later. Then the user will call the constexpr method for this intermediate result if he wants to get char* , but one character can be obtained using the constexpr function. It would be an unorthodox version of sprintf , I'm not sure if it will be considered at all.

+2
source

I am also looking for the same solution. I believe it is possible if the format string refers only to data of a fixed length (static_assert will help). In this case, the length of the result buffer can be calculated at compile time by summing the length of the format string without placeholders, the maximum length of the string representation of each argument and cell for the null terminator. The main goal is to have something like std :: array buffer; _snprint_f (buffer, "% d - 0x% p", some_integer, some_pointer);

You could even use std :: a fixed-length data array as an argument ...

0
source

All Articles