Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a object (class) foreachable in D?

how can I make a class usable in a foreach statement?

The class contains a associative array (e.g. string[string]). So the foreach statement use this array as source.

So this is what I want:

auto obj = new Obj();
foreach (key, value; obj)
{
    ...
}

Do I need to implement a interface someting like that?

EDIT:

The solution:

public int opApply(int delegate(ref string, ref Type) dg)
{
    int result = 0;

    foreach (ref key, ref value; data)
    {
        result = dg(key, value);
        if (result != 0)
        {
            break;
        }
    }

    return result;
}

Same is done for public int opApply(int delegate(ref Type) dg).

like image 671
VDVLeon Avatar asked Jun 15 '10 15:06

VDVLeon


1 Answers

D1:

class Foo
{
    uint array[2];

    int opApply(int delegate(ref uint) dg)
    {
        int result = 0;

        for (int i = 0; i < array.length; i++)
        {
            result = dg(array[i]);
            if (result)
                break;
        }
        return result;
    }
}

D2:

Iteration over struct and class objects can be done with ranges, which means [a set of] properties must be defined:

like image 197
Vladimir Panteleev Avatar answered Jan 06 '23 13:01

Vladimir Panteleev