digitalmars.D.learn - Implicit conversion of char[] to string struct
- Alan Smith <alanrogersmith gmail.com> Dec 30 2007
- Matti Niemenmaa <see_signature for.real.address> Dec 30 2007
Hi,
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));
All help is appreciated!
Peace, Alan
Dec 30 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
Dec 30 2007








Matti Niemenmaa <see_signature for.real.address>