'Helper' functions in C++

前端 未结 7 931
轻奢々
轻奢々 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:12

    Copied/trimmed/reworked part of my answer from How do you properly use namespaces in C++?.

    Using "using"

    You can use "using" to avoid repeating the "prefixing" of your helper function. for example:

    struct AAA
    {
       void makeSomething() ;
    } ;
    
    namespace BBB
    {
       void makeSomethingElse() ;
    }
    
    void willCompile()
    {
       AAA::makeSomething() ;
       BBB::makeSomethingElse() ;
    }
    
    void willCompileAgain()
    {
       using BBB ;
    
       makeSomethingElse() ; // This will call BBB::makeSomethingElse()
    }
    
    void WONT_COMPILE()
    {
       using AAA ; // ERROR : Won't compile
    
       makeSomething() ; // ERROR : Won't compile
    }
    

    Namespace Composition

    Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".

    In the "Special Edition", at 8.2.8 Namespace Composition, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:

    namespace AAA
    {
       void doSomething() ;
    }
    
    namespace BBB
    {
       void doSomethingElse() ;
    }
    
    namespace CCC
    {
       using namespace AAA ;
       using namespace BBB ;
    }
    
    void doSomethingAgain()
    {
       CCC::doSomething() ;
       CCC::doSomethingElse() ;
    }
    

    You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.

提交回复
热议问题