Multiple namespace declaration in C++

2019-02-02 08:22发布

Is it legal to replace something like this:

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

with something like this:

namespace foo::bar {
   baz();
}

?

7条回答
再贱就再见
2楼-- · 2019-02-02 08:33

Qualified names, like something::someting_else in C++ can only be used to refer to entities that have already been declared before. 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.

查看更多
不美不萌又怎样
3楼-- · 2019-02-02 08:34

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

Update:

You can now nest namespaces more cleanly in C++17:

namespace Foo::Bar::YetAnother {
  // do something even fancier!
}
查看更多
4楼-- · 2019-02-02 08:35

As per the grammar in $2.10, an identifier cannot have the token ":". So the name foo::bar is ill-formed.

查看更多
地球回转人心会变
5楼-- · 2019-02-02 08:37

For anyone wondering, the form namespace foo::bar is supported since C++17. References:

查看更多
淡お忘
6楼-- · 2019-02-02 08:51

No; it's a syntax error.

查看更多
淡お忘
7楼-- · 2019-02-02 08:54

You can combine namespaces into one name and use the new name (i.e. Foobar).

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

namespace Foobar = Foo::Bar;

int main()
{
    Foobar::some_func();
}
查看更多
登录 后发表回答