Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for anonymous namespaces in header-only libraries

Tags:

c++

I understand why it doesn't make sense to use anonymous namespaces in header files... They aren't really anonymous...

However, this begs the question:

Is there an alternative idiom/mechanism to avoid polluting the global namespace when distributing a header-only library?

EDIT:

My typical usage of an anonymous namespace is to keep some block of code local to a file so that it doesn't pollute the global namespace. For e.g. if some class had some magic constant, then instead of declaring a global static int, I could declare it in the cpp file:

namespace{
    int magic = 5;
}

Is there a way to achieve the same effect without having to use a cpp file?

like image 593
bremen_matt Avatar asked Oct 26 '25 07:10

bremen_matt


2 Answers

C++ doesn't have any mechanism to make entities in header files completely invisible to users. They can be made inaccessible if you want. This is normally achieved by member access control. You have to make foo_impl a private (possibly static) member of some class. Overloads of foo would then be either members or friends of the same class.

Alternatively, if you make foo_impl a member of a namespace named detail or foo_private or some such, users will normally understand they should not call this function. This works well in practice. Users will still be able to access the function at their own risk, but they will understand the risk. This should be plenty enough, as C++ doesn't protect you from malicious users anyway.

like image 200
n. 1.8e9-where's-my-share m. Avatar answered Oct 28 '25 22:10

n. 1.8e9-where's-my-share m.


In boost, there is sometimes used namespace named detail

Functions not intended for use by applications are in boost::math::detail.

like image 21
Luka Rahne Avatar answered Oct 28 '25 21:10

Luka Rahne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!