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?
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.
In boost, there is sometimes used namespace named detail
Functions not intended for use by applications are in
boost::math::detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With