简体   繁体   English

仅标头库中匿名名称空间的替代方法

[英]Alternative for anonymous namespaces in header-only libraries

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 eg if some class had some magic constant, then instead of declaring a global static int, I could declare it in the cpp file: 例如,如果某个类具有一些魔术常数,则可以在cpp文件中声明它,而不是声明一个全局静态int:

namespace{
    int magic = 5;
}

Is there a way to achieve the same effect without having to use a cpp file? 有没有一种方法可以不必使用cpp文件来达到相同的效果?

In boost , there is sometimes used namespace named detail boost中 ,有时会使用命名为detail命名空间。

Functions not intended for use by applications are in boost::math::detail . 不适用于应用程序的功能在boost::math::detail

C++ doesn't have any mechanism to make entities in header files completely invisible to users. C ++没有任何机制可以使头文件中的实体对用户完全不可见 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. 您必须使foo_impl成为某个类的私有(可能是静态)成员。 Overloads of foo would then be either members or friends of the same class. 然后, foo重载将是同一类的成员或朋友。

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. 或者,如果使foo_impl成为名为detailfoo_private或类似名称的命名空间的成员,则用户通常会理解他们不应调用此函数。 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. 这应该足够了,因为C ++仍然无法保护您免受恶意用户的侵害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM