Quote:Original post by suliman
there is some problem with the casting and i dont get it to work. And i need it to return a pointer anyway, so I tried to fix it and clean it up, but it doesnt work... (slump is my random int generator)
template<typename T>typename T* getRandom(T & list){ return= std::advance(list.begin(),slump(0,list.size()));}unit * u = getRandom(unitList);
//initializing' : cannot convert from 'class std::list<class unit *,class std::allocator<class unit *> > *' to 'class unit *'
This happens because you changed the code without understanding what it does. In my code, T is a container type (list, vector, deque). You kept this property by keeping the argument T & list. So, your modified function returns a pointer to a list. See where the contradiction is?
My original code returned an iterator inside the list. This allows me to avoid having to look into the type of the list to determine what kind of object it contains. This makes the code simpler and also lets it work with less effort on other containers (should you, for instance, use a vector instead of a list). Besides, your code assumes that the function would somehow return a pointer, because you know that your list contains pointers — but, again, you're losing genericity since you'll have to write a non-pointer version for other list types.
In short, keep the function general (although you may specialize the random number generator if you wish) and dereference the returned iterator to get the element.
template<typename Container>typename Container::iterator & getRandom(Container & list){ return std::advance(list.begin(),slump(0,list.size()));}unit * u = * getRandom(unitList);