How can I stop letting other clutter / expand my namespace?
Suppose, if I have a namespace
in one header file. I don't want that people should be able to expand it to other files. Is it possible in C++ ?
开发者_如何学C//N.h
namespace N {
//...
}
//Other.h
#include"N.h"
namespace N { // <--- don't allow this
void foo () {}
}
[Note: Asking this for knowledge and curiosity. Because, have heard many times that one should not expand std
.]
AFAIK, you can't do this in C++, and I don't see any practical reason for it either.
You can wrap your code into a class instead of a namespace; since a class declaration cannot be spread over several headers, others cannot add to it.
But again, I don't see why you think this is a problem, and I'd be curious to see an example.
You can only ask people to behave, not force them. Perhaps you can try this:
namespace milind
{
namespace Private
{
// Please don't add stuff to my private namespace
... Important implementation details goes here
}
}
You could use a class with all statics instead of a namespace to simulate the behavior.
Found one way. I can encapsulate the namespace
inside another dummy type of namespace
and then use it. To avoid verbosity, we can use an alias to the existing namespace
.
i.e.
//N.h
namespace DUMMY_ { // <--- put a dummy outer namespace
namespace N {
//...
}
}
namespace N = DUMMY_::N; // alias the name to the original name
//Other.h
#include"N.h"
namespace N { // <--- error !!
void foo () {}
}
Edit: With above solution it's less likely that people would expand namespace N
. However, as @Charles comment, still DUMMY_
is visible to the reader. Which means one can still do like:
namespace DUMMY_ {
namespace N { // ok
void foo () {}
}
}
So only way remains to prohibit the undesired expansion is by replacing:
namespace N = DUMMY_::N;
with,
#define N DUMMY_::N
This will work as per expected; but we enter the region of macros.
精彩评论