When D is not nice

JAnderson ask at me.com
Thu Jul 10 00:08:39 PDT 2008


Tomas Lindquist Olsen wrote:
> JAnderson wrote:
>> Frank Benoit wrote:
>>> String concatenation in Java:
>>>
>>> "abc " + a + " bla";
>>>
>>> where a is an interface ref.
>>>
>>> Ported to D, this look like this:
>>>
>>> "abc " ~ (cast(Object)a).toString ~ " bla";
>>>
>>> This are 3 steps more:
>>> 1.) explicit cast to Object (interface/class compatibility!)
>>> 2.) explicit call to toString
>>> 3.) put additional parentheses
>>>
>>> I would be happy if we could remove all three of this annoying points.
>>
>> I agree, string handling could be better its such a common operation. 
>> Its one of worst things to work with in C++.  Implicit string 
>> conversions would make things much easier and more readable.
>>
>> -Joel
> 
> I think STL solves this quite nicely with std::ostringstream ... Though 
> I might be misunderstanding you...
> 
> Tomas

I don;t like std::ostringstream.

- Its hard to debug.
- Your always converting one string to a std::string (and then perhaps a 
C string)
.  You can't pass it into a function that takes a string ie:

foo("test" << 5); //You couldn't do this for instance.  And this is very 
useful.

- You have to define a specific overload for every special case.  These 
are not as reuseable in other cases as a common sense ".ToString()"
- It doesn't allocate very effectively.
- You have to include the large std::ostringstream.
- A personal preference: I think std::ostringstream (and its variants) 
are ugly.  In particular the shift operations are nasty.
- You can't remove a piece of another string very easily (string 
manipulation and transforms).

Lets compare:
#include <sstream>
...
   ostringstream oss;
   oss << str << t2;
   std::string result=oss.str();
   Foo(result.c_str());

*sign* ok you could do this:

   ostringstream oss;
   oss << str << t2;
   Foo(oss.str().c_str());

To:
   Foo(str ~ T2);

What would you prefer?

Don't get me wrong.  I do use std::ostringstream however its just I 
don't like it compared to say... VB.

I use this in C++ normally:

template <class out_type, class in_value>
out_type convert(const in_value & t)
{
  stringstream stream;
  stream << t; // insert value to stream
  out_type result; // store conversion’s result here
  stream >> result; // write value to result
  return result;
}

...

Foo((str + convert(T2)).c_str());

All I want to do is send a dam message with some value attached to the 
end. I shouldn't have to jump though hoops to do so.

-Joel



More information about the Digitalmars-d mailing list