C++: Namespaces — How to use in header and source files correctly?

前端 未结 5 1472
走了就别回头了
走了就别回头了 2021-01-30 00:42

Consider a pair of two source files: an interface declaration file (*.h or *.hpp) and its implementation file (*.cpp).

Let the

5条回答
  •  长情又很酷
    2021-01-30 01:04

    I'd like also to add that if you decide due to some reason to implement a template specialization in a cpp file and just rely on using namespace you will run into the following problem:

    // .h file
    namespace someNameSpace
    {
      template
        class Demo
        {
          void foo();
        };
    }
    
    // .cpp file
    using namespace someNameSpace;
    
    template
    void Demo::foo(){}
    
    // this will produce
    // error: specialization of 'template void someNameSpace::Demo::foo()' in different namespace [-fpermissive]
    template<>
    void Demo::foo(){}
    

    Otherwise if you apply #2 method this will be fine.

提交回复
热议问题