views:

141

answers:

6

Is it legal to replace something like this:

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

with something like this:

namespace foo::bar {
   baz();
}

?

+1  A: 

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 '{'

Dean Harding
Note: Just because something works or does not work with a particular compiler does not mean it's standards or not standards compliant.
Billy ONeal
@Billy: Something working does not mean anything. Something *not* working does. If your compiler doesn't support a feature, then you can't use it, whatever the standard says on the subject.
Dennis Zickefoose
@Dennis: While this is true, the OP didn't ask for whether or not his or her compiler would support it, (s)he asked if it was valid.
Billy ONeal
+3  A: 

No; it's a syntax error.

Porculus
+6  A: 

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
NuSkooler
+11  A: 

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();
}
skimobear
+1 for information he couldn't have gotten by just asking his compiler.
Dennis Zickefoose
+5  A: 

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.

AndreyT
A: 

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

Chubsdad
That doesn't mean much, without also showing that an identifier is needed here. `foo::bar` is obviously valid sometimes.
Dennis Zickefoose