Implementing “foreach” for custom containers

Foreach

The “foreach” loop is a special case of the for loop, usually enacted on a linear container such as an array or a list, where for every iteration of the loop, some action is performed on a member of the container until that action has been performed on every element in the collection.

Some languages, such as perl, javascript, and java have an explicit foreach instruction. in Perl for example we can do:

C++ does have the enhanced for loop which allows us to perform foreach-like iteratrions on containers:

But what about if we’ve coded our own container, and want to implement a generic foreach function for it?

 

Function Pointers to the rescue!

So we’ve implemented our container, and what to extend the functionality of said container by being able to performa an operation on each element without having to create a whole new method each time. By utilizing the function pointers we are able to implement the visitor pattern to accomplish our goal.

The visitor pattern implements a “visitor object” that performs the desired action on each member as it “visits” the element. In our case, the visitor will be a function pointer. Inside our class we declare a method, forEach(), which will take as its parameter, a function pointer, and as it performs a traversal of the container it will call the function pointed to by the function pointer on each member of the container:

So here we have a very simple linked list container that supports 2 methods, push() which adds an item to the list, and the previously mentioned forEach function:

So now we have the capability to add an item to the list, and perform an action on every list member. Lets see how we can display every item on the list:

I took the opportunity there to show that you can pass a lambda as the requisite function pointer, but you can also pass a pointer to any function you want!

Increasing functionality

Now that you get the main gist of how to implement a foreach function for your containers, you can further expand the functionality, by implementing return types, variadic parameters, etc. As with everything in programming, the only limit is your imagination!

So with another tool for the tool box, get out there and write some code. Until next time, keep coding!

Leave a Reply

Your email address will not be published. Required fields are marked *