How can I stop using another space / extension of my namespace?

Suppose if I have a namespace in a single header file. I do not want people to be able to expand it to other files. Is this possible in C ++?

 //Nh namespace N { //... } //Other.h #include"Nh" namespace N { // <--- don't allow this void foo () {} } 

[Note: ask about this for knowledge and curiosity. Because you have heard many times that you should not extend std .]

+4
source share
4 answers

AFAIK, you cannot do this in C ++, and I see no practical reason for this.

You can wrap your code in a class instead of a namespace; since a class declaration cannot be extended to multiple headers, others cannot add to it.

But then again, I donโ€™t understand why you think this is a problem, and I would be curious to see an example.

+4
source

You can only ask people to act, and not force them. Perhaps you can try the following:

 namespace milind { namespace Private { // Please don't add stuff to my private namespace ... Important implementation details goes here } } 
+1
source

You can use a class with all the statics instead of a namespace to mimic the behavior.

0
source

One way found. I can encapsulate namespace inside another dummy type namespace and then use it. To avoid details, we can use an alias for an existing namespace .

i.e.

 //Nh namespace DUMMY_ { // <--- put a dummy outer namespace namespace N { //... } } namespace N = DUMMY_::N; // alias the name to the original name //Other.h #include"Nh" namespace N { // <--- error !! void foo () {} } 

Change With the above solution, it is less likely that people will extend namespace N However, as @Charles comment, still DUMMY_ displayed to the reader. This means that you can still:

 namespace DUMMY_ { namespace N { // ok void foo () {} } } 

Thus, it remains only to prohibit unwanted expansion, replacing:

 namespace N = DUMMY_::N; 

with,

 #define N DUMMY_::N 

This will work as expected; but we enter the macro area.

0
source

All Articles