How to create a virtual type to provide that this structure has some kind of field with @xxxx annotation?

I would like to create a virtual structure, I mean as Input Range. You can create a new type of structure and be an input range. I know who use duck print :-)

In my case, I would like to use duck print if any type have the given attribute. By expression, if at least one field is like @MyUDA

with this i could send any type of structure to a function

struct MyUDA {}

struct A {
  @MyUDA int a1;
  @MyUDA float a2;
}


strct B {
  @MyUDA string b;
}

A a;
B b;
foo( a );
foo( b );

I hope this is enough.

+4
source share
1 answer

The key is to use a constraint with an auxiliary function:

enum MyUDA; // instead of struct so @MyUDA works instead of @MyUDA()

struct A {
  @MyUDA int a1;
  @MyUDA float a2;
}


struct B {
  @MyUDA string b;
}

void main() {
    A a;
    B b;
    foo( a );
    foo( b );
}

// this looks for the uda on a member
template HasMyUDA(T) {
    static bool helper() {
        foreach(memberName; __traits(allMembers, T)) {
            foreach(attr; __traits(getAttributes, __traits(getMember, T, memberName)))
                static if(is(attr == MyUDA))
                    return true;
        }
        return false;
    }

    enum HasMyUDA = helper();
}

// test usage
void foo(T)(T t) if(HasMyUDA!T) {
    pragma(msg, T.stringof ~ " works here");
}

, -, , , .

+4

Source: https://habr.com/ru/post/1542066/


All Articles