Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::format() accept different string types for format and arguments?

Tags:

c++

printf

With printf I can do something like this

wprintf(L"%hs", "abc");

where the format is wchar_t * but argument is char *. Is this doable with std::format(), or do I have to convert one to the other prior?

When I do

std::format(L"{:hs}", "abc");

I get compile error about type mismatch.

like image 828
Crend King Avatar asked Sep 15 '25 21:09

Crend King


1 Answers

It cannot.

As per the documentation, the format string matches Python’s format specification, which does not have any magic for directly dealing with different string types or encodings. (Python does everything behind the scenes with CESU-8, IIRC.)

This is one of those things where I wish the C++ Standard would just Do The Right Thing™, but as the C++ Standards Committee still hasn’t hashed out how they want to handle string encoding transformations (as of Jan 2022) we are stuck with a dumb std::format.

The ultimate goal, I think (and hope), is that std::format will one day accept different string types and transform them properly for you without having to change the fmt argument. For now, however, you must perform the transform yourself.

Alas, ATM std::format will only accept like string types for all arguments, where the base character type is either char or wchar_t. That’s it. (More docs.)

like image 126
Dúthomhas Avatar answered Sep 17 '25 10:09

Dúthomhas