On 24 mar, 15:38, Ricky65 <ricky...@hotmail.com> wrote:
> I was thinking about string formatting after reading this article by
> Herb Sutter here:http://www.gotw.ca/publications/mill19.htm
>
> I thought to myself "Why haven't they overloaded the << operator for
> the basic_string class?" like with the iostream.
Who is "they" ? The standard committee ?
> I don't think I'm the
> first to have thought of this. I assume performance problems are the
> reason this is not done.
Doing so would shun formating facilities.
The language definition is geared toward general case. If you have
specific needs, you are expected to roll your own. This avoid
cluttering the standard with use cases that you can recode or that
libraries can provide.
> This would eliminate the need to make a temporary variable to hold the
> formatted data like a stringstream does and the problems with the
> sprintf family. I know a lot of people shun stringstreams because they
> are unacceptably slow in some cases.
I expect that using a temporary stringstream is more efficient than
appending into a string.
>
> For example, we could do something like this:
> int cat_len = 120;
> int mouse_len = 29;
>
> std::string myformattedstring << "The cat is " << a << "cm tall and
> the mouse is " << b << "cm tall.";
>
> As you can see, this would format directly to the string. This would
> be both type safe and length safe and the programmer wouldn't have to
> allocate a temporary variable for a stream. However, I'm not sure how
> efficient it would be. I'm intrigued to know if this can be done and
> and if not, the reasons why.
As you wrote it, it is impossible: you cannot mix variable definition
and initialization this way.
Something possible is:
std::string myformattedstring = string_formater()<<"The cat is "
<<...;
Some very fast formating constructs based on template can be designed
this way ( especially if the maximum size of each element can be
computed beforehand). But they have some limitations.
If you want to see an example, you can lookup the FastFormat library
from Matthew Wilson and its shims technique.
Concerning the form, I'd prefer:
std::string myformattedstring = ("The cat is ",fmt::_1,"cm tall and
the mouse is ",fmt::_2,"cm tall.")
, cat_len, mouse_len;
--
Michael