DEV Community

Discussion on: How do I use variable-arguments (varargs) in C++ (effectively)?

Collapse
 
baenencalin profile image
Calin Baenen

@omercsp Since I got tread-locked, I thought I'd leave my response to a good point you made in this reply.

If a language provides you the facility to do something, you need a very very good reason to not use it for the same task. So far, no such reason was provided.

Excluding snprintf, C++ only has one way of doing "formatting", stringstreams.

std::stringstream strs;
std::string str  = "My Str";
strs << s << "ing.";
strs.str(); // "My String.". - This was concatenation.
Enter fullscreen mode Exit fullscreen mode

This solution works well with a finite number of arguments, but when you need an unpredictable or changing amount; it gets hard to manage.
One may decide to make multiple function overloads for them to format their string, but this bloats the code, and requiring lots of overloads will make things harder to manage.
A negligible nitpick is that it looks bulky. - I heard it described as verbose. But, it's not. It's just bulky.

snprintf definitely is the way to go.

My opinion is just that C++ swung and missed here.

Collapse
 
pgradot profile image
Pierre Gradot

Since C++20, you have std::format() en.cppreference.com/w/cpp/utility/...

You can also you the great fmt library fmt.dev/latest/index.html

Collapse
 
baenencalin profile image
Calin Baenen • Edited

Since C++20, you have std::format() en.cppreference.com/w/cpp/utility/...

I tried. I don't.
G++ (11.1.0 (GCC)) on Arch Linux (x86_64) says the format header does not exist.

I'm not aware of how to install the format header.

Thread Thread
 
pgradot profile image
Pierre Gradot

en.cppreference.com/w/cpp/compiler... : it seems that no compiler has support for at the moment...

std::format() is just a function that you have in the fmt library. I believe everybody keeps using it ^^