[Effective-cpp] Item 1: Uses and Abuses of vector

Ric Parkin ric.parkin at ntlworld.com
Wed Oct 27 04:33:54 EDT 2004


From: "Timothy C. Wright" <tim at tcw321.com>
> If the functor is small and can be written near the for_each call, I 
> think for_each is easier to read and type then hand coding the loop.  


Right - it splits the mechanics of the loop from the mechanics to work on each item. With a good descriptive name, of course. 

> But if I needed to store the functors somewhere else for sharing, I can 
> see the problems. I have had second thoughts on the code because all 
> these functors scattered all over.

This is the sort of organisational area that's quite new, but not so new that I'd expect some experience to have been accumulated.

So, how have people tried to organise libraries of functors, predicates, algorithms etc? Which things worked, which didn't? Ideas to try next time?

I've tended to notice three approaches, all of which are useful at some point:

- at point of use (or near enough), often in an anonymous namespace. Quick and dirty. Often pretty hardcoded, to a type, and sometimes to values. Candidates to be pulled out into a library if similarities start to turn up. Downside, is hard to find to spot similarities.

- Next to type definitions. Will have to be commonly used, eg specialisation of std::swap, sorting predicates for a name type (first name, last name etc). Downside of the specialisations is that that will drag in the primary template definition even if not needed, but moving the specialisation away from the type can cause bugs if it's not visible. Anyone managed to solve this?

- In a sperate header. I've done this for related functors - eg for a family of deleter functions to clear out containers of pointers. (delete_pointer, delete_array, delete_second etc). But sometimes it's not clear where a functor should go, and you end up with either a dumping ground algorithm header, or loads of tiny one-functor headers.

Ric




-----------------------------------------
Email provided by http://www.ntlhome.com/





More information about the Effective-cpp mailing list