www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can functions add properties?

reply "Jun" <ltalbsjea gmail.com> writes:
I found some codes write

toStringz(myString)

as

mystring.toStringz

So I tested this code myself and it worked.

int pow2(int i)
{
     return i*i;
}
int myint = 5;
int otherint = myint.pow2;
assert(otherint == 25);

I've never seen any documentation about this behaviour. I think 
it's a good feature, but I'm a bit confused.
Nov 23 2012
next sibling parent "Mike Parker" <aldacron gmail.com> writes:
On Friday, 23 November 2012 at 14:08:05 UTC, Jun wrote:
 I found some codes write

 toStringz(myString)

 as

 mystring.toStringz

 So I tested this code myself and it worked.

 int pow2(int i)
 {
     return i*i;
 }
 int myint = 5;
 int otherint = myint.pow2;
 assert(otherint == 25);
FYI, you could even do this: int otherint = 5.pow2;
 I've never seen any documentation about this behaviour. I think 
 it's a good feature, but I'm a bit confused.
It's called Universal Function Call Syntax (UFCS). The compiler essentially rewrites something.function to function(something), unless "something" is a struct or class with a method named "function", in which case it calls the method instead.
Nov 23 2012
prev sibling parent "Rob T" <rob ucora.com> writes:
On Friday, 23 November 2012 at 14:08:05 UTC, Jun wrote:
 I've never seen any documentation about this behaviour. I think 
 it's a good feature, but I'm a bit confused.
More info here http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394 UFCS is relatively new and has not been included in the language documentation yet. It was added to the language only a few months ago with the dmd 2.059 release. IMO it should be in the docs by now, and I think that's a problem area being worked (I hope). --rt
Nov 23 2012