Make a namespace private in C++
Asked Answered
C

3

5

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?

Ciao answered 13/7, 2015 at 9:32 Comment(2)
You cannot really prevent from someone else extending your namespace. But I've seen additional namespaces like internal_ are used to make it clear for every one.Scriven
You don't put data in namespaces in C++. You put that kind of data in classes as static data and you can make that private. PS: I'm not even sure what you mean by data. It would be nice to see some sample concept code in the question.Rubiaceous
D
5

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

Diluvial answered 13/7, 2015 at 9:35 Comment(2)
Edit the header?? How??Ciao
I don't understant the reasoning. What's stopping you from editing his source files, changing everything as the way you want.Authority
B
7

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.

Benedix answered 13/7, 2015 at 9:35 Comment(0)
D
5

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

Diluvial answered 13/7, 2015 at 9:35 Comment(2)
Edit the header?? How??Ciao
I don't understant the reasoning. What's stopping you from editing his source files, changing everything as the way you want.Authority
S
1

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.

Stefaniestefano answered 13/7, 2015 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.