Multiple namespace declaration in C++

后端 未结 7 1336
无人共我
无人共我 2020-12-28 17:30

Is it legal to replace something like this:

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

with something like this:



        
相关标签:
7条回答
  • 2020-12-28 18:00

    Did you try it? Visual C++ gives me the following errors:

    1>C:\...\foo.cpp(31): error C2061: syntax error : identifier 'bar'
    1>C:\...\fooo.cpp(31): error C2143: syntax error : missing ';' before '{'

    0 讨论(0)
  • 2020-12-28 18:01

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

    • http://en.cppreference.com/w/cpp/language/namespace
    • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4230.html
    0 讨论(0)
  • 2020-12-28 18:03

    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();
    }
    
    0 讨论(0)
  • 2020-12-28 18:07

    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.

    0 讨论(0)
  • 2020-12-28 18:11

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

    0 讨论(0)
  • 2020-12-28 18:15

    Pre 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:

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

    namespace Foo::Bar::YetAnother {
      // do something even fancier!
    }
    
    0 讨论(0)
提交回复
热议问题