Implicit conversion of char[] to string struct
Matti Niemenmaa
see_signature at for.real.address
Sun Dec 30 09:24:44 PST 2007
Alan Smith wrote:
> I would like to know if it is possible to convert a char[] to a struct that
> has a opCall(char[] str) function. For example:
>
> import std.stdio;
>
> char firstCharacterInString(pstring str) { return str[0]; }
>
> void main() { writefln("first char = '%s'", firstCharacterInString("Hello World!")); // should print "first char = 'H'" }
>
> pstring = http://www.dprogramming.com/dstring.php
>
> The above code will output something like this:
>
> Error: cannot implicitly convert expression ("Hello World!") of type
> char[12u] to pstring
>
> Is there any way to make D substitute "Hello World!" for pstring("Hello
> World!")? How do I get the above code to work without creating an instance of
> pstring like this:
>
> pstring str = "Hello World!";
>
> writefln("first char = '%s'", firstCharacterInString(str));
You can't do it with structs, as far as I can tell.
If pstring were a class, you could do this:
import std.stdio;
class pstring {
char[] foo;
this(char[] s) {
foo = s;
}
}
// note the ellipsis
char firstCharacterInString(pstring str...) {
return str.foo[0];
}
void main() {
writefln("first char = '%s'", firstCharacterInString("Hello World!"));
}
Perhaps if, in the future, structs get constructors, you could do something like
this with structs.
Of course, you're free to make a wrapper class for your struct but that's
somewhat self-defeating in my opinion. :-)
--
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi
More information about the Digitalmars-d-learn
mailing list