Determining whether a class has a method

Bill Baxter dnewsgroup at billbaxter.com
Thu Nov 29 16:49:03 PST 2007


Christopher Wright wrote:
> Hey all,
> 
> I'm trying to determine whether a class has a method (at compile time, 
> based on the name), and ideally I want to do this is D1 as well as D2. 
> In D2, I can just use __traits, of course.
> 
> I could try doing something like:
> 
> bool has_method(T, string name)() {
>     foreach (method; T.tupleof) {
>         if (method.stringof == name) {
>             return true;
>         }
>     }
>     return false;
> }
> 
> But tupleof fails if you give it a class that has fields (methods are 
> fine, but data fields aren't). I'm pretty sure this is a bug; can anyone 
> else comment on it?
> 
> Is there a way to do this in D1?

I think you may be able to use an 'is' check + string mixin if the name 
string is a compile time constant.
like
    static if(is( T.name == function ))

then mixin-ify that like

bool has_method(T, string name) {
    mixin("static if(is T."~name~" == function)) "
          "{ return true; } else {return false; }");
}


--bb


More information about the Digitalmars-d-learn mailing list