Defining a class within a namespace

Iraimbilanja picture Iraimbilanja · Mar 8, 2009 · Viewed 48.9k times · Source

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.

Answer

D.Shawley picture D.Shawley · Mar 8, 2009

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).