Template magic exercise

anonymous anonymous at example.com
Sun Mar 30 06:25:53 PDT 2014


On Sunday, 30 March 2014 at 12:42:16 UTC, Jack Applegame wrote:
> Target is to create a template for mapping member "array 
> accessor" to member function.
>
> For example:
>
> class Foo {
>   ...
>   int elementsAccessor(size_t index) { ... }
>   ...
>   mixin MagicTemplateMixin!("elements", elementsAccessor);
>   // or better
>   alias elements = SuperMagicTemplate!elementsAccessor;
> }
>
> and now we can call Foo.getter like this:
>
> auto foo = new Foo;
> int el = foo.elements[10]; // int el = foo.getter(10);
>
> I wrote poor and ugly solution with proxy structure:
> http://dpaste.dzfl.pl/93085910f8c7
> I hate it. :)
>
> I need more powerful spell, but my magic level is too low.

Maybe less is more here:

---
struct OpIndexFromAccessor(R, PS) {
      R delegate(PS) dg;
      R opIndex(PS ps) { return dg(ps); }
}
auto opIndexFromAccessor(R, PS)(R delegate(PS) accessor) {
      return OpIndexFromAccessor!(R, PS)(accessor);
}
class Foo {
      int elementsAccessor(size_t index) { ... }
      auto elements() {return
opIndexFromAccessor(&elementsAccessor);}
          /* This is hardly more complex than the mixin or alias
variants. */
}
---


More information about the Digitalmars-d-learn mailing list