'Helper' functions in C++

前端 未结 7 780
轻奢々
轻奢々 2021-02-01 03:20

While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don\'t operate on any member data or call any othe

7条回答
  •  离开以前
    2021-02-01 04:10

    To add to Pieter's excellent response, another advantage of namespaces is that you can forward declare stuff that you put in a namespace somewhere else, especially structs...

    //Header a.h
    // Lots of big header files, spreading throughout your code
    class foo
    {
      struct bar {/* ... */);
    };
    
    //header b.h
    #include a.h // Required, no way around it, pulls in big headers
    class b
    {
      //...
      DoSomething(foo::bar);
    };
    

    And with namespaces...

    //Header a.h
    // Big header files
    namespace foo
    {
      struct bar {/* ... */);
    }
    
    //header b.h
    // Avoid include, instead forward declare 
    //  (can put forward declares in a _fwd.h file)
    namespace foo
    {
      struct bar;
    }
    
    class b
    {
      //...
      // note that foo:bar must be passed by reference or pointer
      void DoSomething(const foo::bar & o);
    };
    

    Forward declares make a big difference to your compile times after small header changes once you end up with a project spanning hundreds of source files.

    Edit from paercebal

    The answer was too good to let it die because of an enum error (see comments). I replaced enums (which can be forward-declared only in C++0x, not in today C++) by structs.

提交回复
热议问题