Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred namespace syntax for source files

Tags:

c++

namespaces

Assuming a class called Bar in a namespace called foo, which syntax do you prefer for your source (.cpp/.cc) file?

namespace foo {
...
void Bar::SomeMethod()
{
    ...
}

} // foo

or

void foo::Bar::SomeMethod()
{
    ...
}

I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?

like image 479
Rob Avatar asked Feb 02 '26 23:02

Rob


2 Answers

I would decline the first (edit : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:

namespace bar { 
     struct foo { void f(); };
}

namespace baz { 
    struct foo { void f(); };
}

using namespace bar;
using namespace baz;

void foo::f() { // which foo??

}

Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous.

Personally i would do it like this:

namespace foo {
void Bar::SomeMethod() {
    // something in here
}
}

It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo.

The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?

like image 138
Johannes Schaub - litb Avatar answered Feb 05 '26 11:02

Johannes Schaub - litb


I prefer an option not listed:

namespace foo {

void Bar::SomeMethod()
{
    ...
}

}  // foo namespace

Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win.

like image 32
hazzen Avatar answered Feb 05 '26 12:02

hazzen