Family of function pointers

The following code is working
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum MonsterName {Goblins, Hobgoblins, Ghouls, ...};

template <class MONSTER, typename T = int>
std::vector<Monster*> createMonsters() { 
// ...
}

std::vector<Monster*> createSpecificMonsters (MonsterName monsterName) {
	switch (monsterName) {
		case Goblins:  return createMonsters<Goblin>();
		case Hobgoblins:  return createMonsters<Hobgoblin>();
		case Ghouls:  return createMonsters<Ghoul>();
		// etc...
	}
}


But apart from the problem of using all these switch cases for every type of monster, what about the problem where I want to use another function with template parameter MONSTER than createMonsters<MONSTER>? Writing out all these cases again certainly is not cool. But a template cannot create a family of function pointers in c++, and a function pointer used in place of createMonsters would be ideal here. So what is the best thing to do? There are going to be hundreds of different Monster derived classes of class Monster. Any way to map MonsterName elements to Monster derived classes? Anyway to iterate through the derived classes of Monster?
Last edited on
I would recommend you looking into Factory pattern, it's probably what you're looking for.

And secondly, check out this:
http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html

it's one of many tutorials about rvalue and move semantics. Using techniques described in this article could speed up your code - your function createSpecificMonsters() may be really slow - first, you have to create a vector, and then fill it and return it, COPYING its content(and you actually do it twice - once in crateSpecificMonsters, and once in createMonsters) - so you're copying same vector twice. If vector is large enough, this can be really slow.

Cheers!
Topic archived. No new replies allowed.