c++ - Namespace + functions versus static methods on a class -
let's have, or going write, set of related functions. let's they're math-related. organizationally, should i:
- write these functions , put them in
mymath
namespace , refer them viamymath::xyz()
- create class called
mymath
, make these methods static , refermymath::xyz()
why choose 1 on other means of organizing software?
by default, use namespaced functions.
classes build objects, not replace namespaces.
in object oriented code
scott meyers wrote whole item effective c++ book on topic, "prefer non-member non-friend functions member functions". found online reference principle in article herb sutter: http://www.gotw.ca/gotw/084.htm
the important thing know that: in c++ functions in same namespace class belong class' interface (because adl search functions when resolving function calls).
namespaced functions, unless declared "friend," have no access class' internals, whereas static methods have.
this means, example, when maintaining class, if need change class' internals, need search side effects in methods, including static ones.
extension i
adding code class' interface.
in c#, can add methods class if have no access it. in c++, impossible.
but, still in c++, can still add namespaced function, class wrote you.
see other side, important when designing code, because putting functions in namespace, authorize users increase/complete class' interface.
extension ii
a side-effect of previous point, impossible declare static methods in multiple headers. every methods must declared in same class.
for namespaces, functions same namespace can declared in multiple headers (the almost-standard swap function best example of that).
extension iii
the basic cooless of namespace in code, can avoid mentioning it, if use keyword "using":
#include <string> #include <vector> // etc. { using namespace std ; // now, std accessible without qualification string s ; // ok vector v ; // ok } string ss ; // compilation error vector vv ; // compilation error
and can limit "pollution" 1 class:
#include <string> #include <vector> { using std::string ; string s ; // ok vector v ; // compilation error } string ss ; // compilation error vector vv ; // compilation error
this "pattern" mandatory proper use of almost-standard swap idiom.
and impossible static methods in classes.
so, c++ namespaces have own semantics.
but goes further, can combine namespaces in way similar inheritance.
for example, if have namespace function aaa, namespace b function bbb, can declare namespace c, , bring aaa , bbb in namespace keyword using.
conclusion
namespaces namespaces. classes classes.
c++ designed each concept different, , used differently, in different cases, solution different problems.
don't use classes when need namespaces.
and in case, need namespaces.
Comments
Post a Comment