views:

693

answers:

5

Is there a more succinct way to define a class in a namespace than this:

namespace ns { class A {}; }

I was hoping something like class ns::A {}; would work, but alas not.

A: 

I haven't checked recently, but class ns::A {} should work, I believe. As long as the ns namespace is previously declared, I believe it should be legal.

jalf
Well, how about you do check before shooting off answers?
A: 

No you can't. To quote the C++ standard, section 3.3.5:

A name declared outside all named or unnamed namespaces (7.3), blocks (6.3), fun (8.3.5), function definitions (8.4) and classes (clause 9) has global namespace scope

So the declaration must be inside a namespace block - the definition can of course be outside it.

anon
well, class A{}; is a definition, not a declaration. Are you sure the quote is applicable, then?
definitions are declarations
anon
um that was not well thought out - but I'm prety sure the quote applies - I'll take another look.
anon
+5  A: 

You're close, you can forward declare the class in the namespace and then define it outside if you want:

namespace ns {
    class A; // just tell the compiler to expect a class def
}

class ns::A {
    // define here
};

What you cannot do is define the class in the namespace without members and then define the class again outside of the namespace. That violates the One Definition Rule (or somesuch nonsense).

D.Shawley
thanks. that's not more succinct but it does seem to make sense.
I don't think that there really is a more succinct or readable version than `namespace ns { class A {}; }` but it is probably just personal opinion.
D.Shawley
+1  A: 

The section you should be reading is this:

7.3.1.2 Namespace member definitions

3 Every name first declared in a namespace is a member of that namespace.[...]

Note the term -- declaration so D.Shawley (and his example) is correct.

dirkgently
+1  A: 

You can do that, but it's not really more succint.

namespace ns {
    class A;
}

class ns::A {
};

Or

namespace ns {
    class B;
}

using ns::B;
class B {
};
Logan Capaldo