简体   繁体   English

C++ 中的多命名空间声明

[英]Multiple namespace declaration in C++

Is it legal to replace something like this:替换这样的东西是否合法:

namespace foo {
   namespace bar {
      baz();
   }
}

with something like this:像这样:

namespace foo::bar {
   baz();
}

? ?

You can combine namespaces into one name and use the new name (ie Foobar).您可以将命名空间合并为一个名称并使用新名称(即 Foobar)。

namespace Foo { namespace Bar {
    void some_func() {
        printf("Hello World.");
    }
}}

namespace Foobar = Foo::Bar;

int main()
{
    Foobar::some_func();
}

Pre C++17 : C++17 之前

No, it's not.不,这不对。 Instead of a bunch of indented nested namespaces, it's certainly valid to put them on the same line:将它们放在同一行上当然是有效的,而不是一堆缩进的嵌套命名空间:

namespace Foo { namespace Bar { namespace YetAnother {
    // do something fancy
} } } // end Foo::Bar::YetAnother namespace

C++17 Update : C++17 更新

You can now nest namespaces more cleanly in C++17 : 您现在可以在 C++17 中更干净地嵌套命名空间

namespace Foo::Bar::YetAnother {
  // do something even fancier!
}

For anyone wondering, the form namespace foo::bar is supported since C++17.对于任何想知道的人来说,从 C++17 开始就支持表单namespace foo::bar References:参考:

Qualified names, like something::someting_else in C++ can only be used to refer to entities that have already been declared before.限定名称,如 C++ 中的something::someting_else只能用于引用之前已经声明的实体。 You cannot use such names to introduce something previously unknown.你不能用这样的名字来介绍以前未知的东西。 Even if the nested namespace was already declared before, extending that namespace is also considered as "introducing something new", so the qualified name is not allowed.即使之前已经声明了嵌套命名空间,扩展该命名空间也被视为“引入新事物”,因此不允许使用限定名称。

You can use such names for defining functions previously declared in the namespace您可以使用这样的名称来定义先前在命名空间中声明的函数

namespace foo {
  namespace bar {
    int baz();
  }
}

// Define
int foo::bar::baz() {
  /* ... */
}

but not declaring new namespaces of extending existing ones.但不声明扩展现有命名空间的新命名空间。

No;不; it's a syntax error.这是一个语法错误。

Did you try it?你试了吗? Visual C++ gives me the following errors: Visual C++ 给了我以下错误:

1>C:\\...\\foo.cpp(31): error C2061: syntax error : identifier 'bar' 1>C:\\...\\foo.cpp(31): error C2061: 语法错误: identifier 'bar'
1>C:\\...\\fooo.cpp(31): error C2143: syntax error : missing ';' 1>C:\\...\\fooo.cpp(31): error C2143: 语法错误: 缺少';' before '{'前 '{'

As per the grammar in $2.10, an identifier cannot have the token ":" .根据 $2.10 中的语法,标识符不能有标记":" So the name foo::bar is ill-formed.所以名称foo::bar格式错误。

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

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