My intuitive answer is yes, and the implementation could also be used by a "printf". And it might be easy to overload for user-defined types.
Has anyone ever attempted this before?
I believe you can't - the main problem would be how would you get the result out of 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) is quite clearly disallowed
(2) is against the contract of sprintf
(ie. a non-constexpr
sprintf
mustn't do that either)
(3) assignment is not possible in constexpr
.
If you just want "something like sprintf
", regardless of possibly inconvenient usage, something eg. with interface like this would work:
my_sprintf<my_string<'%', 'd', '%', 'c'>, my_data<int, 42>, my_data<char, 'l'> >::string_value
On second thought, you could avoid actually computing the string and just store the parameters of the sprintf
invocation for later. The user would then call a non-constexpr
method of that intermediate result if he wanted to get a char*
, but a single character could be obtained by a constexpr
function. That would be an unorthodox version of sprintf
, I'm not sure if it would count at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With