How/why can toStringz() and toUTFz() be used as properties?

anonymous anonymous at example.com
Fri Apr 26 01:49:09 PDT 2013


On Friday, 26 April 2013 at 07:31:57 UTC, Trey Brisbane wrote:
> Hey all,
>
> Can someone please explain to me how and why it is that 
> toStringz() and toUTFz() can be used in the following way?
>
> string a = "123";
> auto b = a.toStringz;
> auto c = a.toUTFz;
>
> Also, how is it that they can even be called as if they were 
> class methods? That is:
>
> string a = "123";
> auto b = a.toStringz(); // <-- Note I've added parentheses
> auto c = a.toUTFz();
>
> As opposed to being limited to:
>
> string a = "123";
> auto b = toStringz(a);
> auto c = toUTFz(a);

There's two things at work here:

a) Universal Function Call Syntax (UFCS). That basically means 
that you can call a free function via method/property-like dot 
syntax. The first argument to the function goes before the dot. 
UFCS should be explained in the online language documentation, 
but if it's in there I can't find it.
So, with UFCS you get from  toStringz(a)  to  a.toStringz() .

b) Empty parentheses are optional. -- Unless you compile with the 
-property flag. There has been some discussion about the future 
of the feature. Optional empty parentheses and/or the -property 
flag may go away in the future.
That gets you from  a.toString()  to  a.toString .

> I need to understand this, as I wish to write a function 
> toWinStr() that can be used in the same way which will accept 
> any string type, and, based on something like version(Unicode) 
> and const-ness, output a WinAPI LPSTR, LPCSTR, LPWSTR or 
> LPCWSTR as appropriate.
> Is such a thing possible?

You just write your function so that  toWinStr(stuff)  works. 
UFCS and optional empty parentheses then enable  stuff.toWinStr .


More information about the Digitalmars-d-learn mailing list