Monday, February 04, 2008

The other ternary operator

There is an interesting stain on OO languages like C++ and Java, namely with member function invocation. Normally, complex expression can be taken apart, and the intermediate value stored in a variable. int a = 2 * (3 +1); can equally be written int helper = 3 +1; int a = 2 * helper;. However, this breaks with obj.meth (). When you try instead to say helper = obj.meth; helper ();, you will run into a problem: What is the type of helper? It should be a function pointer/reference. Java does not even have functions; in C++ you are equally at a loss for a proper type. (I'm not going into that actually the parameter types aka signature form a part of the method name.)

Indeed the compilers simply go to treat the combination a.b(c) as a single operator. In Java the method and member name spaces are actually separate; a method can have the same name as a member. (Does that make it a Java-2?)

The only language that makes this explicit is Lua. Member invocation is obj:meth(arg), which is the same as obj.meth(obj,arg) (except that obj is only evaluated once).

I don't know of any language that does it properly. Even though a member function exists as code only once, logically there is a distinct function for each object. The member selection needs to bind the function code address and the object pointer together, into something that is quite similar to a closure.

1 comment:

helium said...

C#?

delegate void MethodType();

class MyClass {
void method ()
{ ... }
}

...

var obj = new MyClass();

MethodType tmp = obj.method;

tmp();


Not perfect but close.