string is rarely useful as a function argument

Adam D. Ruppe destructionator at gmail.com
Wed Dec 28 22:01:55 PST 2011


On Thursday, 29 December 2011 at 05:37:00 UTC, Walter Bright 
wrote:
> I've seen the damage done in C++ with multiple string types. 
> Being able to convert from one to the other doesn't help much.

Note that I'm on your side here re strings, but you're
underselling the D language too! These conversions
are implicit both ways, and completely free. D structs
can wrap other D types perfectly well.

Check this out:

string a = "hello";
a = a.replace("h", "j");
assert(a == "jello");

this actually works, today, with a custom string type
in the D language. Just define a struct string in your
module. alias this does most the magic.

In C++, std::string and char* are very different.

===
#include<string>

void a(const char* str) {}

int main() {
	std::string me = "lol"; // works
	a(me); // ...but this doesn't work
	return 0;
}
===


But, in D, that *does work*. A struct string
can be used on a function that calls for a const(char)[].
It can be used for a function that calls for an immutable(char)[].
It can be used for a function that calls for a struct string.

A string struct works exactly the same way as a string alias.

Right down to the name!



It's not storeable in a variable typed char[] (or
wchar[] nor dchar[]), but neither are D strings
today.



More information about the Digitalmars-d mailing list