Preferred namespace syntax for source files - c++

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?

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?

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.

I'd rather go for the first case, where namespaces are explicitly marked:
namespace TheNamespace {
void TheClass::TheMethod() {
// code
}
}
The reason is that it is clear from that syntax that TheClass is a class and TheNamespace is a namespace (not so obvious by any other names). If the code were
void TheNamespace::TheClass::TheMethod() {
// code
}
then a reader does not clearly see whether TheNamespace is a namespace, or a class with an inside class by the name of TheClass.
class TheClass1
{
class TheClass2
{
void TheMethod();
}
};
void TheClass1::TheClass2::TheMethod() {
// code
}
I tend to avoid the 'using' statement, and even then the example by litb with two classes in two different namespaces will make both the compiler and the programmer confused and should be avoided.

I think it depends on each case. If it's a 3rd party library that's similar to your own code, and you want to avoid confusion in the code, then specifying the full namespace at each occurance may be beneficial. But other than that, less code is generally better (unless it becomes unclear).

Related

Invoke a method without using the class name and scope resolution operator

When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std;
How can I do this with a user-defined class or is it impossible. (No pre-processor macro solution please). I tried using this:
#include <iostream>
using namespace std;
namespace std
{
class A
{
public:
static void foo()
{
std::cout << "foo";
}
};
}
int main ()
{
//foo(); does not work
A::foo(); //Only this works
}
Replacing std by any other namespaces also doesn't work.
When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std; How can I do this with a user-defined class [...]
std::sort is a template not a function, but otherwise it is not different from code you can write yourself:
namespace foo {
void bar() {}
}
using namespace foo;
int main() {
bar(); // ok
}
This works for namespaces but not for members of classes (there is using for members of classes to bring something from a base class scope into the derived class scope, but thats a different topic and beyond the scope of the question (no pun intended), it is not what you are asking for here).
In your example there is no reason why foo should be a member of A, hence you should make it a free function (as above). Supposed you didn't write A but you still need to call it without qualifiying the class name you can wrap it in a free function.
Also note that you are not allowed to add something to namespace std. If you do, your code has undefined behavior.
And finally, note that there are good reasons to discourge usage of using some_namespace; altogether. Consider this:
namespace foo1 {
void bar(){}
}
namespace foo2 {
void bar(){}
}
// lots of other code
using namespace foo1;
// lots of other code
int main() {
foo1::bar(); // this is bar from foo1
foo2::bar(); // this is bar from foo2
bar(); // to know which bar this is you have to
// look for any using directive, ie
// it makes your code much harder to read
}
Code is written once but read many times. The 6 extra characters to type pay off in more clear code. See also:
Why is “using namespace std;” considered bad practice?

C++ method implementations: Can I avoid typing the class name each time?

When I have a C++ class MyClass in namespace mynamespace, I implement its methods as
void mynamespace::MyClass::method() { … }
I can wrap that in a namespace to shorten individual definitions to
namespace mynamespace {
void MyClass::method() { ... }
}
Is there a way to avoid having to retype MyClass:: as well so I can copy everything before the { to the header as a prototype more easily whenever the signature changes, without having to remove the MyClass:: every time?
I thought "a class is also a namespace, maybe I can do"
namespace mynamespace::MyClass {
void method() { ... }
}
but that complains that I was re-defining MyClass as a different thing. using mynamespace::MyClass; also didn't work (but would be bad anyway because how would I declare a standalone function anywhere below that line in that file if it worked).
Is there a solution to this, or is it simply not possible in C++?
No, the qualified class name must appear on any class member defined outside the class definition. (And there can only be one class definition, which is normally in a header file.)
The C++ Standard spells out this rule in [class.mfct]/4:
If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the ​::​ operator.
and similarly in [class.static.data]/2 for static data members.
You might abbreviate this qualification using preprocessor macros, but that would seriously harm legibility and is not a common practice.
There is no idiomatic way to avoid this. Even if you or someone else might come up with a "hack" (macro-based, for example), it would make the code less readable for everyone. The normal and expected way to write C++ is for the member functions to have the preceding MyClass:: when defined outside the class definition.
I would suggest to look for a tool that can update signatures between header and source file on command.
Or, as the comments suggest, provide the definitions of your functions right with the declaration inside the class definition (i.e. provide inline definitions). But that has its own disadvantages.
Using C++20 modules, you can implement a class in one file:
module myproject.mymodule;
namespace mynamespace {
export struct my_class {
auto my_method() -> int {
return 8;
}
};
}
Or export a whole namespace fragment:
export namespace mynamespace {
struct my_class {
auto my_method() -> int {
return 8;
}
};
auto also_exported() -> void {
// ...
}
}
Then, instead of including it, you can import that module:
import myproject.mymodule;
auto frob() -> void {
auto my_instance = mynamespace::my_class{};
}

C++ Should I fully qualified my variable type?

I am trying to write lines of code fitting under 80 columns maximum. Thus, I wonder if fully qualifying my variable type is really mandatory ? Assuming the following implementation:
//Baz.h
namespace loggingapi {
namespace attributes {
class Baz {};
}} // namespaces
// Bar.h
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(Baz* b);
};
} // namespaces
To declare my function parameter type, there are multiple ways ?
a) int f(Baz* b);
b) OR int f(attributes::Baz* b);
c) OR int f(loggingapi::attributes::Baz* b);
d) OR int f(::loggingapi::attributes::Baz* b);
In the list above, which definition(s) is/are clearer/ambiguous for the compilers ?
NOTE: You must assume the namespace/parameter/class/function names CANNOT be shortened in the following implementation.
Variant e ?
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
typedef attributes::Baz Baz;
// C++ 11 alternative
// using Baz = attributes::Baz;
int f(Baz* b);
}
} // namespaces
Do not forget what aliasing can do for you...
I would go with the b) variant. My reasons are as follows:
We assume that the developer knows in what namespace he is now. So when looking at the class Biz, the developer should know that this class is in the loggingapi namespace, therefore, there's no need to explicitly state it.
The a) variant, on the other hand, isn't clear enough, because we should indicate that Baz and Biz are actually in different namespaces. Also, it is not going compile, because the compiler will look for Baz in the loggingapi namespace, and it isn't there.
You should choose (b). It's more flexible. If you decide to move or (gasp) cut and paste f and it's related types to a new namespace or project then using (b) ensures that the structure of the declarations remains internally consistent.
You can choose to add, remove or rename outer wrapping namespaces without affecting the enclosed code.
In h-file it is better to use fully qualified names, to prevent possible ambiguity in a client code. In .cpp file you can use short notation, if you prefer this, as long as there is no name clash.
If a compiler has some ambiguity it will definitely report an error.
I believe the question should be with respect to the human reader, which is quite subjective.
The naming convention depends on
Pre-decided coding style
Where you are declaring the function f()
There is no clear choice over another. I would prefer that, if both entities are belonging to same namespace then I will omit at least that part from the name:
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(attribute::Baz* b);
}; // ^^^^^^^^^^^^^
}

Using-directive class static functions?

I am using an API that has a lot of functions in a class named TCODConsole as static functions. Now I thought that it was in a namespace, so I wrote: using namespace TCODConsole;. Then I found out that TCODConsole ain't a namespace, but a class.
Is there a way to import those functions in a similar way as you would use using namespace?
No, there is no shortcut way to call myStaticFun() instead of MyClass::myStaticFun(). You cannot do that with class. It's a class, not a namespace. But you can write something like a wrapper. That is you will add functions with same name and call the static methods from that functions. Something like this:
class MyClass {
static void fun();
};
void fun() {
MyClass::fun();
}
// call it
fun();
Not a very good way. Personally I think it is better to stick with the class instead of doing this.
Though I may misunderstand the question,
if shortening the qualification is the objective,
does typedefing like the following meet the purpose?
struct TCODConsole {
static void f();
static void g();
};
int main() {
typedef TCODConsole T;
T::f();
T::g();
}
Alternatively, if the class TCODConsole can be instantiated,
since static member function can be called with the same form as
non-static member function, the following code might meet the purpose:
int main() {
TCODConsole t;
t.f();
t.g();
}
I can't think of a clean way to do it, but I can think of a kinda ugly hack that will work, as long as the code using it is part of a class (and if TCODConsole really contains only static member functions). Let's say you are bar(), a member function of the class Foo, and you want to call a function baz() which is a static member of TCODConsole without fully-qualifying it. What you can do is to privately derive Foo from TCODConsole:
class Foo : private TCODConsole
{
void bar()
{
baz();
}
};
Yeah, that's ugly. :(
If you want to use Boost.PP (the Boost Preprocessor macro library - you don't need to compile or include anything else from Boost to use it), you can probably make a less ugly but quite a bit more convoluted macro which will "import" these functions for you, by wrapping them with inline functions inside another namespace (which you can then import at will). It would still require you to explicitly specify the name each of the functions you want to "import", so your code (minus the macro) will look something like this:
namespace TCODStatic
{
IMPORT_FROM_TCOD(foo)
IMPORT_FROM_TCOD(bar)
IMPORT_FROM_TCOD(baz)
IMPORT_FROM_TCOD(spaz)
}
and then you'll be able to write using namespace TCODStatic; anywhere you want.
Short answer: not without using macros. There is no mechanism in the C++ language proper to do something like this:
class A
{
public:
static void foo();
};
// ...
using A;
foo();
You could use a macro to build these expressions for you:
#define FOO() (A::foo())
FOO();
I would discourage this however, because it can become a maintennence nightmare is you make extensive use of such macros. You end up with code like this:
FOO();
BAR();
SUPERGIZMO(a, b, c);
...where none of these things are defined as first-class names anywhere in the program. You've lost all type checking, the code uses a "secret language" that only you know, and it becomes difficult to debug, extend and fix.
EDIT:
You could write a kind of bridge. Like this:
class FooBar
{
public:
static void gizmo();
};
namespace Foo
{
void gizmo() { FooBar::gizmo(); };
};
using namespace Foo;
gizmo();

Template / Namespace Interactions

I came across a compile.. oddity? recently that led me to believe that a template, when created, is created in the same namespaces (or, at least, using the same namespaces) as where is was declared. That is;
template<class T>
class bar
{
public:
static int stuff(){return T::stuff();}
};
namespace ONE
{
struct foo
{
static int stuff(){return 1;}
};
}
namespace TWO
{
struct foo
{
static int stuff(){return 2;}
};
}
using namespace TWO;
int main()
{
return bar<foo>::stuff();
}
will return 1 when using namespace ONE and 2 when using namespace TWO.
Why? And are there other "odd" or "unexpected" interactions between namespaces and templates?
Edit: This was confusing at the time because the same templates were being used across multiple files, each using a different namespace.
That's not unexpected. You didn't qualify which foo you wanted, so your using declaration told the compiler where to find it.
The worst template gotcha I've seen in production code had to do with non-dependent name lookup. It's pretty complicated, so it's probably best to just point you at the C++ FAQ Lite (sections 35.18-20).
I'm not sure what's surprising here. When you say using namespace ONE you bring ONE::foo to scope, now recognized as foo. In the above code the template gets TWO::foo as its parameter. It has nothing to do with the template, everything that's going on is going on in main() when you call bar<T>::stuff().