简体   繁体   English

具有内部链接的命名命名空间

[英]Named namespace with internal linkage

[@PasserBy has found that my question is a duplicate. [@PasserBy发现我的问题是重复的。 The question can be closed, thanks.] 问题可以结束,谢谢。]

How can I get a named namespace with internal linkage? 如何获得具有内部链接的命名命名空间? That is, how can I get a named namespace invisible to external source files? 也就是说,如何才能使命名的命名空间对外部源文件不可见? I want this: 我要这个:

static namespace N {
    int foo() {return 10;}
    int bar() {return 20;}
}

However, unfortunately, C++ does not recognize static namespace . 但是,遗憾的是,C ++无法识别static namespace

Enclose the named namespace within an unnamed namespace: 将命名的命名空间包含在未命名的命名空间中:

namespace {
    namespace N {
        int foo() {return 10;}
        int bar() {return 20;}
    }
}

int sum()
{
    return N::foo() + N::bar();
}

This works because an unnamed namespace automatically exports its members (the sole member in this case being the namespace N ) to the surrounding scope—without exposing the members to other source files. 这是有效的,因为未命名的命名空间会自动将其成员(在这种情况下唯一的成员是名称空间N )导出到周围的作用域 - 而不会将成员公开给其他源文件。

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

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