c++ - Why do generic programming designs prefer free functions over member functions? -


i got introduced design of generic programming libraries stl, boost::graph, boost propertymaps http://www.boost.org/doc/libs/1_54_0/libs/property_map/doc/property_map.html

what rationale behind using free functions get(propertymap, key) on member functions propertymap.get(key)?

i understand generic form of these functions defined in "boost" namespace. suppose define new propertymap in namespace "project", best place define it's corresponding "get" function? "boost" or "project"

the main motivation preferring nonmember nonfriend functions helps keep classes concise possible. see herb sutter's article here: http://www.gotw.ca/publications/mill02.htm.

this article contains answer other part of question, put corresponding function. it's feature of c++ called argument dependent lookup (adl). herb sutter, calls koenig lookup although name controversial (see comments below):

koenig lookup says that, if supply function argument of class type, find function name compiler required look, not in usual places local scope, in namespace (here ns) contains argument's type.

here's example:

namespace mynamespace {     class myclass {... };     void func(myclass); }  int main(int aargc, char* aargv[]) {     mynamespace::myclass inst;     func(inst);  // ok, because koenig says in argument's namespace func } 

so in short, declare function in same namespace class.

be aware doesn't work templated functions if have supply template parameters explicitly -- see post: https://stackoverflow.com/a/2953783/27130


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -