Eduard Rostomyan
Eduard Rostomyan

Reputation: 6546

Make a namespace private in C++

Consider this case. I am writing a library and want to wrap my data in a namespace. For example:

//header.h
#pragma once

namespace wrapper
{
    // some interface functions here..
}

And I want to make my namespace private. So that no one can write anything in it. For instance, we can always write something like this.

namespace std
{
    // some data here..
}

So I want to prevent the last case. Is there any technique to do that besides using static functions wrapped in a class?

Upvotes: 5

Views: 4510

Answers (3)

Niall
Niall

Reputation: 30606

A namespace cannot be made private, there is no access control (i.e. similar to a class) for a namespace. Even without attempting to edit the header file, the namespace can always be added to.

Alternatives include;

  • Put the data into the cpp file, still in a namespace if desired. Thus the data is not "private" but since it is not in the header it is also not "visible" to the client.

  • This is possibly better but may require more effort given the question; is to make use of the "pimpl" (or private class data) idiom to "hide" the data in the class from the client. The bridge pattern could also be used.

Upvotes: 1

Oswald
Oswald

Reputation: 31637

This is not possible. If all else fails, I can always edit your header file.

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234635

No there isn't. A namespace can always be added to, unless it's an anonymous namespace. But they can only feasibly reside in a single compilation unit.

Upvotes: 7

Related Questions