views:

230

answers:

4

I have a small namespace containing some type definitions, which I use to make my code look cleaner. However I don't want to have to add a "using namespace ..." line to every file that uses one of these types, after all I already have to add a #include for the file.


MyFile.cpp:

#include "typedefs.h"
void Bob()
{
 IntList^ list = gcnew IntList;
}


typedefs.h:

namespace Typedefs
{
 typedef List<int> IntList;
 typedef array<int> IntArray;
 typedef List<Byte> ByteList;
 typedef array<Byte> ByteArray;
 typedef List<String^> StringList;
 typedef array<String^> StringArray;
}
using namespace Typedefs;


Would it be acceptable to add the "using namespace" line immediately after the namespace declaration? If not, why not?

+3  A: 

It's possible but I don't think it's wise. It just defeats the whole purpose of the namespace by exposing its contents everywhere. If you want the comfort of not having to specify Typedefs:: or using Typedefs::xxx; or using namespace Typedefs; I'd just not create a namespace at all.

jpalecek
A: 

You might as well define your new types outside any namespace, or am I missing something?

João da Silva
+1  A: 

Putting a 'using namespace XXX;' directive into a header file is usually considered to be a bad idea, as it does defeat the idea of having a namespace in the first place. It can easily lead to the sort of naming conflicts that the introduction of a namespace is supposed to avoid.

My advice - don't do it, if necessary stick them into the appropriate source files (.cpp) instead.

Timo Geusch
+1  A: 

Use unnamednamespace.If you want to have the names visible only to the files in which you have included the headers

namespace {
  int i = 10;
}

above has the same effect as like below code

namespace randomName {
  int i = 10;
}
using randomName;

so nothing will be accessible from any other file.

yesraaj
Thanks. I looked into your answer and found it reiterated in http://winterdom.com/dev/cpp/nspaces.html
demoncodemonkey