getAttr method

guillaume Chéreau charlie137 at gmail.com
Fri Feb 1 10:20:48 PST 2008


bearophile Wrote:

> Guillaume Chéreau:
> >and it can be useful sometime.
> 
> Can you show one or more (practical) examples of situations where it can be useful?

It could be useful to create 'decorator' objects. That is an object that encapsulate an other object and redirect all the methods except a particular one. This can be used for iterators.

ex : (I will suppose we also have a function glob_getAttr(o)(name) that calls the method with the given name of the object o)

Class Decorator(T) {
    T obj;

    this(T obj) {this.obj = obj;}
    typeof(glob_getAttr!(T)(name)) getAttr(string name)() {
        return glob_getAttr(obj, name);
   }
   int x() {return 2 * obj.x();}
}

void main() {
    A a = new A();
    auto d = new Decorator!(A)(a);
    d.f // return a.f
    d.x // return 2 * a.x
}

OK, as I write it i realize how more useful and simple this kind of things are in python than in compiled language.
Maybe it is not as good an idea as I though after all :)

Guillaume


> 
> Bye,
> bearophile




More information about the Digitalmars-d mailing list