using __traits to get line number of a member

forkit forkit at gmail.com
Sun Nov 14 04:05:45 UTC 2021


On Saturday, 13 November 2021 at 17:22:16 UTC, Stanislav Blinov 
wrote:
> On Saturday, 13 November 2021 at 08:04:56 UTC, forkit wrote:
>
>>     int i;
>>     foreach(m; __traits(allMembers, mixin(__MODULE__)))
>>     // ...
>>     __traits(getLocation, mixin(m))[1]);
>
> What you really should be doing is this:
>
> ```d
> static import mod = mixin(__MODULE__);
> foreach (i, name; __traits(allMembers, mod))
> {
>    // ...
>    __traits(getLocation, __traits(getMember, mod, i));
>    // ...
> }
> ```
>
> Otherwise you might run into name conflicts, and get location 
> of a wrong symbol.
>
> Also if you really want to be generic you should couple it with 
> `__traits(getOverloads)`, like the docs for getLocation suggest.

static import mod = mixin(__MODULE__);

That statement above would not compile. After spending way too 
much time trying to work out, I gave up, and used what i have, 
which works.

I just want to know, which members in my module are functions, 
and which are classes. I got the isFunction  (that method exists)

However, there is no isClass method. Why not?

How do I determine if a member is a class.. I wonder...

e.g.

//=========================
module test;

import std;

class myClass{} // nothing to see here

void main()
{
     alias allMembersOfThisModule = __traits(allMembers, 
mixin(__MODULE__));
     string memberFile() { return `__traits(getLocation, 
mixin(member))[0]`; }
     string memberLocation() { return `__traits(getLocation, 
mixin(member))[1]`; }

     foreach(member; allMembersOfThisModule)
     {
         static if(member == "std" || member == "object")
         {
             continue;
         }
         else
         {
             writefln("\nHere is a member: %s", member);

             // what kind of member is it?
             if(isFunction!(mixin(member)))
                 writeln("This is a function.");
             //else
             //if(isClass!(mixin(member)))
                //writeln("This is a class.");
             else
                 writeln("Not really sure what type of member this 
is..");

             writefln("%s is located in file: %s", member, 
mixin(memberFile));
             writefln("%s begins on line number: %s", member, 
mixin(memberLocation));
         }
     }
}

void myFunction(){} // nothing to see here

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


More information about the Digitalmars-d-learn mailing list