Using custom attribute for a general parser. Is possible in D ?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 26 12:50:29 PDT 2014


On 05/23/2014 09:09 AM, bioinfornatics wrote:

 > struct A {
 >           @section( ( word ) =>  word[0] == '@', ( word ) =>
 > word[0] == '\n')
 >           int a;
 > }

I was able to make that work if I used function instead of delegate:

import std.stdio;

struct attribute { }

alias MatchFunc = bool function( string );

@attribute
struct section {
      MatchFunc start;
      MatchFunc end;

      this( in MatchFunc start,
            in MatchFunc end)
      {
          this.start  = start,
          this.end    = end;
      }
}

struct A {
     @section((string word) => word[0] == '@',
              (string word) => word[0] == '\n')
     int a;
}

import std.traits;

void main()
{
     auto aa = A();
     auto t = __traits(getAttributes, A.a);

     foreach (sect; t) {
         auto start_result = sect.start("@test");
         auto end_result = sect.end("\n");

         writefln("Results: %s and %s", start_result, end_result);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list