Search code examples
dintrospection

Can "isTemplate" return true for a non-function class member in D?


I've got a list of class members: __traits(allMembers, SomeType). And I use a trait __traits(isTemplate, member) for some element member from the list. Consider the result of the trait is true. Does this mean that the member is a function? Or can something else be template in the list from allMembers?


Solution

  • It doesn't mean it's a function, it means it's a template. That template could either be a templated function, or indeed a template itself.

    An example:

    import std.stdio;
    struct Test{
        void fee(T)(){}
        template fi(T){
            void fo(){} // wont get tested...
        }
        void fum(){}
    } 
    
    void main(){
        foreach(member; __traits(allMembers, Test)){
            writefln("%s isTemplate: %s", member, __traits(isTemplate, mixin("Test."~member)));
        }
    }
    

    Output:

    fee isTemplate: true
    fi isTemplate: true
    fum isTemplate: false
    

    The thing that is probably tripping you up is you lacking the mixin. If mixin("Test."~member) wasn't there, then isTemplate would be testing if fi is a template, or fo or fum, and they're not templates as they dont exist in that namespace.

    They only exist in the Test structs namespace.