Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++/CLI yield?

Tags:

.net

c++-cli

In C#, I can use the yield keyword to implement a generator, viz:

int GenInt()
{
    for(int i = 0; i < 5; i++)
        yield return i;
}

Then, calling the function multiple times will return 0 through 4.

Can the same thing be done in C++/CLI? There's no yield keyword, so my gut reaction is that there isn't, which sucks, but what can you do?

like image 509
Lee Crabtree Avatar asked Jun 05 '09 14:06

Lee Crabtree


1 Answers

Can the same thing be done in C++/CLI? There's no yield keyword, so my gut reaction is that there isn't, which sucks, but what can you do?

yield return in C# is just a shortcut that lets the compiler generate the necessary code for you that implements an implementation of IEnumerable<T> and IEnumerator<T>. Since C++/CLI doesn't offer this service, you've got to do it manually: just write two classes, one that implements each interface (or, doing it like the C# compiler, one class implementing both but this can get messy if the whole thing can be called repeatedly – cue: statefulness).

Here's a small example – since I don't have an IDE and my C++/CLI is a bit rusty, I'll give it in C#:

class MyRange : IEnumerable<int> {
    private class MyRangeIterator : IEnumerator<int> {
        private int i = 0;

        public int Current { get { return i; } }

        object IEnumerator.Current { get { return Current; } }

        public bool MoveNext() { return i++ != 10; }

        public void Dispose() { }

        void IEnumerator.Reset() { throw new NotImplementedException(); }
    }

    public IEnumerator<int> GetEnumerator() { return new MyRangeIterator(); }

    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

// Usage:
foreach (int i in new MyRange())
    Console.WriteLine(i);
like image 177
Konrad Rudolph Avatar answered Sep 23 '22 08:09

Konrad Rudolph