seeding the pot for 2.0 features

Reiner Pope xxxx at xxx.xxx
Sun Jan 28 18:07:30 PST 2007


Wolfgang Draxinger wrote:
> A quite cool feature was something similair to Python's
> __getattr__, __setattr__ special functions.
> 
> So if one writes
> 
> class foo
> {
>         ... // foo does not declare a function or member bar
> 
>         // special operators do not return anything
>         opGetAttr(out T val, char[] identifier);
>         opSetAttr(in T val, char[] identifier);
> };
I think this could be a great feature, but be better as a template, 
because compile-time variables can be accessed at runtime, but not vice 
versa. Also remember that properties can mimic member variables, so 
supporting member functions should be enough. For any arbitrary call like
    foo.bar(a, b, c);
the compiler would then follow the following law: if no member 'bar' is 
found that overloads satisfactorily, try rewriting it to
    foo.opFakeMember!("bar")(a, b, c);
and see if a satisfactory overload can be found.

This would allow more things, yet often keep the overhead restricted to 
compile time.  For instance, you could use this to generate 'swizzling' 
functions, as discussed in the 'small vector' thread above, or generate 
conversions to all possible color spaces (rgba, bgra, etc):

struct MyVector
{
    template opFakeMember(char[] ident)
    {
       static if (ident[0..7] == "swizzle" && ident.length == 11)
           alias swizzle!(ident[7..11]).swizzle opFakeMember;
    }

    MyVector swizzle(char[] order)()
    {
       // Do some more template meta-programming to generate a swizzle
    }
}

And, having it as a template doesn't exclude transmitting the identifier 
at runtime:

class MyDynamicPythonClass
{
    void* opFakeMember(char[] ident)()
    {
       return runPythonLookupToGetThisVariable(ident); // Run at runtime
    }

    void opFakeMember(char[] ident)(void* foo)
    {
        setPythonVariable(ident, foo); // Run at runtime
    }

    unittest
    {
       auto test = new MyDynamicPythonClass();
       test.bar = 5; // Property syntax allows variable mimicry;
       writeflln(test.boom);
    }
}

Cheers,

Reiner



More information about the Digitalmars-d mailing list