c++ 11 features with practical examples (for each or range based loop)

I am going to use a famous example of factory design pattern which creates two stooges.

Stooge class implementation along with factory method is here

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
class Stooge {
public:
	static Stooge *make_stooge(int);
	virtual void tell_a_joke()=0;
};

class Jerry : public Stooge{
public:
	void tell_a_joke(){
		std::cout << "I am jerry the stooge \n";
	}
};

class Moe : public Stooge{
public:
	void tell_a_joke(){
		std::cout << "I am Moe the stooge \n";
	}
};
Stooge *Stooge::make_stooge(int choice)
{
	if (choice == 1)
	{
		return new Jerry;
	}
	else
		return new Moe;
}

In summary a factory pattern takes out burden from “main” function (class consumer normally) to write all the “new” and stuff.

now the main

int main()
	std::vector<Stooge*> circus;
	int choice;
	cin >> choice;
	while (choice != 0)
	{
		cin >> choice;
		circus.push_back(Stooge::make_stooge(choice));
	}

	for each (Stooge* st in circus) st->tell_a_joke();
	cout << " \n Previous to that you have to use mem_fun... see implementation in source code\n";
	for_each(circus.begin(), circus.end(), mem_fun(&Stooge::tell_a_joke));
	cin >> choice;
}

So you can see how using for each looks somewhat comparable to other languages (like python)
The older way (“for_each”) has to provide the address of the static function which requires using “mem_fun” function which in my opinion is ok but error prone

Advertisements