"What I can not create, I do not understand."
- Richard Feynman
Having spent the most part of my programming career using C++, it is even today still a language that continues to impress me on what it is capable of, in term of semantic and syntatic richness. I will chronicle here some of my own experiments with the language, which both serve as a means of documenting what I know and for enhancing my understanding thru being able to explain various C++ concepts.
Inspirations from boost::make_indirect_iterator
I happen to encounter the situation in which I have a container of object pointers on which i need to invoke a particular function.
For example, we have
class MyClass
{
public:
int i;
};
vector<MyClass*> myclasses;
and we want to invoke the function foo,
void foo(MyClass& x)
{
cout << x.i << endl;
}
on MyClass instances in the vector via a for_each loop. But for some reason i'm not allowed to change the function signature. To work around the issue, since the function expects a MyClass& reference, we need some magic via boost's make_indirect_iterator as follow,
for_each(boost::make_indirect_iterator(myclasses.begin()),
boost::make_indirect_iterator(myclasses.end()),
boost::bind(foo, _1));
The above code prints the value of i in each instance of MyClass passed to foo. It quite amazed me that make_indirector_iterator makes everything just work seamlessly, so I spent quite a while thinking about how the internal work of the code might look like. I specifically wanted to figure out the workings of the boost template code that made make_indirector_iterator work. After much thinking and experimenting I kind of figured out an alternative method of achieving the results with the following code,
for_each(vec.begin(), vec.end(),boost::bind(foo, boost::bind(make_indirect<X>,_1)));
Having written down the syntax we can now figure out what sort of code structure would make the above code work the same way as the previous example.