Define a function inside a namespace or qualified?

Viewed 55

I see two styles in our codebase. Simple question: what is to prefer?

void
someNsName::someFunc( int a, int b )
{/*...*/}

void
someNsName::someOtherFunc( int c )
{/*...*/}

or

namespace someNsName {
void
someFunc( int a, int b )
{/*...*/}

void
someOtherFunc( int c )
{/*...*/}
} // NS someNsName

I personally prefer the latter, especially when you would have to qualify a lot from someNsName otherwise. But are there more reasons?

1 Answers

The biggest difference between the two is that a function cannot be first declared by a qualified name.

// header
namespace foo {
    void bar(int);
}

// implementation
namespace foo {
    void bar(long) {
    } 
}

I made a mistake in the argument list. It declares an overload instead of the function I intended. The problem will only likely be caught during linking. Which isn't too bad, but could still take some time to actually popup. Had I written the implementation as

void foo::bar(long) {
}

It would have been an immediate compiler error when the implementation file is compiled. There is no such function previously declared in foo, so I can't define it.

For long namespace lists one could always do

namespace impl = some::other::ns;

void impl::bar() {}

That's the most important difference between the two approaches, I think. But again, both styles have (different) merits, so either one will do so long as we are consistent.

Related