using __traits to get line number of a member

forkit forkit at gmail.com
Sat Nov 13 08:04:56 UTC 2021


On Saturday, 13 November 2021 at 07:20:14 UTC, Ali Çehreli wrote:
>
> It works because we mix-in the value of the string 'm', which 
> becomes a symbol.
>
> ('foreach' instead of 'static foreach' works as well.)
>
> Ali

Thanks. Really appreciate the help provided in this thread :-)

Final working code below:

//===================================

module test;

import std;

class myClass{ void foo(){}}

void myFunction1(){}

void main()
{
     // list the first user defined member of this module (other 
than main)

     int i;
     foreach(m; __traits(allMembers, mixin(__MODULE__)))
     {
         // ignore these members
         static if(m == "std" || m == "object" || m == "main" || m 
== "_d_run_main" || m == "_Dmain"  )
         {
            i = 1;
            continue;
         }
         else
         {
             writefln("The name of the first user member is: %s", 
m);

             // getLocation returns a tuple. See note below
             writefln("%s begins on line number: %s", m, 
__traits(getLocation, mixin(m))[1]);
         }

         if(i == 1) break;
     }
}


void myFunction2(){}


/*
     https://dlang.org/spec/traits.html#getLocation

     get the location of a symbol where the argument was declared.

     getLocation Returns a tuple(string, int, int) whose entries 
correspond to
     [0] string -> the filename
     [1] int -> line number
     [2] int -> column number
*/

// ======================================


More information about the Digitalmars-d-learn mailing list