On Thursday, 30 May 2019 at 18:34:31 UTC, Robert M. Münch wrote:
I have myClass and I want to add a way where I can provide a delegate to iterate over myClass.objects when a member function put(...) of myClass is called. The idea is that a user of myClass can provide something like an "iterator filter" so that the function is only called on a subset of myClass.objects.


myClass(E){
        myOtherClass!E objects;

        void put(E obj) {
                .put(objects, obj);
        }

        void put(T)(E obj, T filter) {
                foreach(o ; filter!E(objects)){
                        .put(o, obj);
                }
        }
}

struct myFilter {
        myOtherClass!E object;

        opApply(int delegate(E) foreach_body) const {
                if(mytestfunc(object))
                        return(foreach_body(object));
        }
}

But I'm struggeling how to write all this down with tempaltes, because E is not known in myFilter. But the filter code needs to be aware of the template type if myClass. I hope the idea want to do is understandable.

Not sure, if I understood your problem correctly. It is meant that the class myClass defines an array of myOtherClass objects? The code does not compile and it does not provide an example, how you would apply the pattern, even in a non-compileable way... However,

commonly, a filter is a higher order function, which expects a predicate acting on each element of a set. Even if it's higher order, it is still a function, not a delegate. Therefore, it is unexpected, that you want to store something inside the filter.

Said this, I for myself had a similar problem. I solved this by reversing the hierarchy: I templated my objects I wanted to use the filter on with the filter function and removed the need of the template parameter inside the filter. You could still write a general filter function in this case, if you want. For example, you could use mixins for this...
As I said... not sure if this is of any help for you...

Reply via email to