The Final(ize) Challenge

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri May 22 21:10:27 PDT 2009


Guillaume B. wrote:
> Andrei Alexandrescu wrote:
>> For starters, I'd like to present you with the following challenge.
>> Given any class C, e.g.:
>>
>> class C
>> {
>>      void foo(int) { ... }
>>      int bar(string) { ... }
>> }
>>
>> define a template class Finalize(T) such that Finalize!(C) is the same
>> as the following hand-written class:
>>
>> final class FinalizeC : C
>> {
>>      final void foo(int a) { return super.foo(a); }
>>      final int bar(string a) { return super.bar(a); }
>> }
>>
>> Finalize is cool when you need some functionality from an exact class
>> and you don't want to pay indirect calls throughout. All calls through
>> Finalize!(C)'s methods will resolve to static calls.
>>
> 
>  Hi,
> 
>  I don't fully understand the uses of Finalize!(C)... But for logging (or
> timing), this kind of template could be useful... it think!... Anyway,
> something like this:
> 
> class MagicLog(T) : T
> {
> // D Magic...
> }
> 
> Could turn a class like this:
> 
> class C
> {
>    int foo() { ... }
> }
> 
> to this:
> 
> class MagicLogC
> {
>    int foo() {
>       Log.write("Entering foo()");
>       scope(success) Log.write("Leaving foo(): success");
>       scope(failure) Log.write("Leaving foo(): failure");
>       return super.foo();
>    }
> }
> 
> And then, somewhere else:
> 
> version(WithMagicLog) {
>    C c = new MagicLog!(C); // With logging
> } else {
>    C c = new C; // Full speed, no logging
> }
> int i = c.foo();
> 
>  Seems pretty useful to me! :) The only problem is writing the MagicLog
> class.

"A simple matter of programming."

It's a great idea, and a means to tap into AOP-style programming by 
using reflection.


Andrei



More information about the Digitalmars-d mailing list