Yes, the syntax is indeed legal, but no, your function actually does live in the namespace NS. The code you are seeing is actually equivalent to
namespace NS { void C::f() { /* ... } }
or to
void NS::C::f() { /* ... */ }
which may be more similiar to what you are used to.
Because of the using-directive you can omit the NS part not only in calling code, but also in its definition. The Standard has an example that matches your code (after the bold emphasized part):
3.4.3.2 Namespace members [namespace.qual]
7 In a declaration for a namespace member in which the declarator-id
is a qualified-id, given that the qualified-id for the namespace
member has the form nested-name-specifier unqualified-id the
unqualified-id shall name a member of the namespace designated by the
nested-name-specifier or of an element of the inline namespace set
(7.3.1) of that namespace. [ Example:
namespace A {
namespace B {
void f1(int);
}
using namespace B;
}
void A::f1(int){ } // ill-formed, f1 is not a member of A
—end example ] However, in such namespace member declarations, the
nested-name-specifier may rely on using-directives to implicitly
provide the initial part of the nested-name-specifier. [ Example:
namespace A {
namespace B {
void f1(int);
}
}
namespace C {
namespace D {
void f1(int);
}
}
using namespace A;
using namespace C::D;
void B::f1(int){ } // OK, defines A::B::f1(int)
—end example ]
So you may omit the initial part of the nested-name-specifier, but not any intermediate part.
C::f()
lives in classC
. – Carvelbuilt