简体   繁体   English

命名空间和自由函数

[英]Namespaces and free functions

I have a free function, foo , defined in a namespace N. The header for foo is in the global include search path so anyone can call it by including foo.h . 我有一个免费的功能, foo ,在一个命名空间为N.头定义foo是在全球包括搜索路径,这样任何人都可以通过包括调用它foo.h

foo calls another local, free function, foo1 , which is defined in foo.cpp . foo调用另一个本地的自由函数foo1 ,它在foo.cpp定义。

// foo.h
namespace N
{
    void foo();
} 


// foo.cpp
#include "foo.h"

namespace
{
    // declare in the unnamed namespace?
    void foo1()
    {
        // do some stuff
    }
}

namespace N
{
    // declare in namespace N?
    void foo1()
    {
        // do some stuff
    }

    void foo()
    {
        foo1();
    }

} // N

Should I put foo1 in the unnamed namespace or in namespace N ? 我应该将foo1放入未命名的命名空间还是namespace N Or doesn't it matter? 或者不重要吗?

UPDATE UPDATE

I want to limit the scope of foo1 to foo.cpp . 我想将foo1的范围限制为foo.cpp

That's not a global namespace, but an anonymous one. 这不是一个全局命名空间,而是一个匿名命名空间。 Defining it there will only allow foo1 to be used in that translation unit, so you can't declare it somewhere else and use it afterwards. 定义它只允许在该翻译单元中使用foo1 ,因此您不能在其他地方声明它并在之后使用它。

This will effectively limit its scope to foo.cpp . 这将有效地将其范围限制为foo.cpp If that's your intention, declare it in an anonymous namespace. 如果这是您的意图,请在匿名命名空间中声明它。

If you want to be able to use it from outside, declare it in the global namespace or N (global namespace means you just leave it out of a namespace) - depending on where it makes sense. 如果您希望能够从外部使用它,请在全局命名空间中声明它或N (全局命名空间意味着您只是将它从命名空间中删除) - 具体取决于它有意义。

void global_foo();

namespace
{
   void internal_linkage_foo();
}

namespace X
{
   void foo_from_x();
}

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

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