Template context

Aarti_pl aarti at interia.pl
Mon Jan 8 04:35:10 PST 2007


Daniel Keep napisał(a):

> 
>> int foo()()
>> {
>>     return foo.context.line;
>> }
> 
> What does that do?  If you can't see what I'm getting at, try this:
> 
>  > class Foo
>  > {
>  >     int line()()
>  >     {
>  >         return line.context.line;
>  >     }
>  > }
> 
> Since we can "call" a parameter-less function without putting in the 
> parens, how do we get to the context?  Making trailing '.'s suppress the 
> function call would make the above style functions even less like real 
> lvalues...
> 

Please notice that problem already exists in current implementation - 
that's nothing new in fact:

class Foo {
	int init() {
		return init.init; //threat init as property
	}
}

This code works - dmd threats init as function call not as function itself.

To disambiguate it would be probably enough to add parenthesis after 
init (line in your example). It could be rule for function properties:

class Foo {
	int init() {
		return init().init; //threat init() as function
	}
}


> 
>  > template tFoo(tArg1, tArg2, context) { }
> 
> But it just seemed... icky.  Hmm... what about...
> 
>  > void trace(T_Args...)(T_Args args...) {
>  >     writef("%s:%d (%s): ", context(trace).file,
>  >         context(trace).line,
>  >         context(trace).symbol);
>  >     foreach( arg ; args )
>  >         writef(arg);
>  >     writefln();
>  > }
> 
> How does that one sit?

I would rather propose another alternative, but not to suppress my 
previous proposition. I see it rather as explication of my previous 
concept, but it could be implemented independently.

There is special keyword in language which points to current object of 
class. It's called "this" and is quite well known ;-)

Why not to extend this idea for other types, e.g. functions. In case of 
function existing keyword "function" could be "pointer" (not literally, 
but semantically) to current function. So that you could write:

class Foo {
	int line()() {
		return function.file.line;
	}
}


Advantages:
1. This syntax would be sometimes more convenient as it is independent 
of function name
2. No new keywords
3. Consistent and expandable

Regarding point 3 of advantages I mean new keyword which could be 
introduced later e.g. "program". This keyword would keep properties for 
program as a whole.

With this extension it would be possible to replace existing __FILE__, 
__LINE__ completely. Imagine this:

void main() {
	writefln(program.file.name, program.file.line);
}

and others nice things as e.g. getting address of main() function:

	program.main

which should allow to recursively call main function if anyone needs 
such a functionality ;-)


Best Regards
Marcin Kuszczak
Aarti_pl



More information about the Digitalmars-d mailing list