Creating a C ++ namespace in the header and source (cpp)

Is there a difference between wrapping the contents of the header content and cpp in the namespace or wrapping only the contents of the header and then using the namespace using the namespace

?

In difference, I mean any arbitrary performance deviation or slightly different semantics that might cause problems or something I need to know.

Example:

// header namespace X { class Foo { public: void TheFunc(); }; } // cpp namespace X { void Foo::TheFunc() { return; } } 

VS

 // header namespace X { class Foo { public: void TheFunc(); }; } // cpp using namespace X; { void Foo::TheFunc() { return; } } 

If it makes no difference, what is the preferred form and why?

+50
c ++ namespaces
Nov 21 '11 at 11:19
source share
6 answers

A namespace is just a way to fake a function's signature so that it does not conflict. Some prefer the first method, while others prefer the second version. Both versions do not affect compilation performance. Note that namespaces are just a compile-time object.

The only problem that arises when using the namespace is that we have the same nested namespace (ie) X :: X :: Foo. In any case, this creates more confusion with or without the use of the keyword.

+23
Nov 21 '11 at 11:27
source share
— -

The difference in the "namespace X" to "use the namespace X" is in the first, all new declarations will be under the namespace, and in the second not.

In your example, there is no new declaration - therefore, there is no difference, therefore, there is no preferred way.

+28
Nov 21 '11 at 11:23
source share

There are no performance penalties since the result may be the same, but casting your Foo to the namespace implicitly introduces ambiguity if you have Foo in different namespaces. You really can get your fubar code. I would recommend avoiding using using for this purpose.

And you have a wandering { after using namespace ; -)

+4
Nov 21 '11 at 11:26
source share

If the second compiles, there should be no difference. Namespaces are processed at compile time and should not affect runtime behavior.

But for design problems, the second is terrible. Even if it compiles (not sure), it makes no sense.

+1
Nov 21 '11 at 11:23
source share

Foo :: TheFunc () is not in the correct namespace in VS-case. Use 'void X :: Foo :: TheFunc () {}' to implement the function in the correct namespace (X).

+1
Nov 21 '11 at 11:24
source share

If you only transfer the contents of .h, you must write using the namespace ... in the cpp file, otherwise you are working on a valid namespace each time. You usually transfer .cpp and .h files, otherwise you run the risk of using objects from a different namespace, which can cause a lot of problems.

0
Nov 21 '11 at 11:27
source share



All Articles