Namespaces

F

Fenton.Barns

I want to wrap a class in a namespace. I've enclosed my class
declaration in a namespace but was wondering what to do in the
implementation file. Should I enclose everything in the same namespace
or should I just add: using namespace foo at the top of my
implementation file? Both appproaches work but I was wondering whether
there are any advantages of using one method over another.

Fenton.
 
J

James Mastro

I want to wrap a class in a namespace. I've enclosed my class
declaration in a namespace but was wondering what to do in the
implementation file. Should I enclose everything in the same namespace
or should I just add: using namespace foo at the top of my
implementation file? Both appproaches work but I was wondering whether
there are any advantages of using one method over another.

I'd go with the enclosing everything in the namespace method. I
wasn't aware the other way was even legal C++.

-jim
 
K

kwikius

I'd go with the enclosing everything in the namespace method. I
wasn't aware the other way was even legal C++.

-jim

FWIW My preference is to qualify each definition in the source file.
e.g:


--my_foo.hpp--

namespace my{
struct foo{
void f();
}
}


--my_foo.cpp--

void my::foo::f()
{
/* ... */
}
---

From a documentation point of view, its much clearer than an enclosing
namespace or a using namespace my, because the documentation is very
localised. Inside the function body it isnt necessary to use the
namespace qualifier but even there, when appropriate, it helps
clarity.

For nested and long named namespaces you could use a

namespace x = very::long_name::nested::x;

etc, but again it reduces clarity of documentation, which is sometimes
not appreciated until it comes to reviewing code especially after 6
months or so, even if you are also the author.

Very often though, you must follow the weird and wonderful coding
standards/guidelines of the company you are working for.

Overall 'using namespace x;' is not 'cool' though IMHO, because it may
make unintended names from namespace x ( and other namespaces too)
visible.

Thats my 2 p's worth anyway.

regards
Andy Little
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,780
Messages
2,569,610
Members
45,254
Latest member
Top Crypto TwitterChannel

Latest Threads

Top