Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

printf

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?

like image 814
rubenvb Avatar asked Feb 02 '13 09:02

rubenvb


1 Answers

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 malloced 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.

like image 187
jpalecek Avatar answered Sep 21 '22 08:09

jpalecek