Why and how should I use namespaces in C++? - c++

I have never used namespaces for my code before. (Other than for using STL functions)
Other than for avoiding name conflicts, is there any other reason to use namespaces?
Do I have to enclose both declarations and definitions in namespace scope?

One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the effect is more implicit, automatic and pervasive - a very powerful language feature.
UPDATE: addressing marcv81's comment...
Why not use an interface with two implementations?
"interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:
the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime
as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation
different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch
with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)
different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless
virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort

Here is a good reason (apart from the obvious stated by you).
Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.
Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).

It can help you for a better comprehension.
eg:
std::func <- all function/class from C++ standard library
lib1::func <- all function/class from specific library
module1::func <-- all function/class for a module of your system
You can also think of it as module in your system.
It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)

Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.
That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.

You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.

Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.
Yes

Related

Is it legal to have 2 header files for the same class in c++?

In a project I read, there are two header files and two declarations for the same class. One is used by programs that use this library, serving as an interface. Another is used by the library itself.The interface header file is simpler. It doesn't contain private members and has less methods. Even methods that appear in both files may not appear in the same order. I wonder if it is legal to have 2 header files for the same class? If it is not, what are the possible consequences?
In short
This is not legal at all. Depending of what's in the private part that is committed, it might work on some implementations, but it might very well fail at the first change or new release of the compiler. Just don't. There are better ways to achieve the intended objectives.
Some more explanations
Why it's not legal?
It's the One Definition Rule (ODR). It's defined in the standard, in a long section [basic.def.odr]. In summary, it is possible to have multiple definition of the same class in different compilation units (e.g. your code, and the library's code), but only if it's exactly the same definition. This requires that it's exactly the same sequence of tokens that are used for the two definitions, which is clearly not the case if you leave out the private members. (Note that there are additional requirements as well, but the first one is already broken, so I short-circuit).
Why does it work in practice in some cases even if not legal?
It's purely implementation dependent luck. I will not develop this topic, in order not to encourage dangerous behavior.
What alternatives
Just use the same definition of the class everywhere. Private members are private, so what's the risk of leaving them where they were ?
Ok, sometimes the definition of private members would require to disclose also private types, end as a chain reaction, much too much. In this case, you may think of:
The simple opaque pointer technique, which uses a pointer to a private implementation class, whose type is declared but that is not defined in the compilation units that do not need to know.
The more elaborate bridge pattern, which allows to build class hierarchies for an abstraction, and class hierarchies with the implementation. It can be used in a similar way than the opaque pointer, but would allow for different kind of private implementation classes (it's a complex pattern, and it's an overkill if it's just for hiding private details).

Is it possible overriding a global implemented function?

I'm being curious about if it is possible to override an implemented function. I mean, is there any legal syntax of function declaration / implementation that allows alternative implementation?
Why am I asking? (I know it sounds ridiculus)
First, just of curiosity and expanding my knowledge.
Second, I've learned that the global new can be overrided (Although it is strongly not recommended).
Third, assume that I have written a library: AwsomeLibrary.hpp, which
my friend wants to include.Among a lot of functions, there is a function like void sort(int* arr), which he thinks that he could implement better (and of course call it with the same name).
I mean, is there any legal syntax of function declaration /
implementation that allows alternative implementation?
No. That would break the one-definition rule (ODR).
Second, I've learned that the global new can be overrided (Although
it is strongly not recommended).
Replaceable allocation functions as documented at http://en.cppreference.com/w/cpp/memory/new/operator_new are really just a very special case, a grey area between language and standard library; certainly not something from which you can infer general rules for your own code.
Third, assume that I have written a library: AwsomeLibrary.hpp, which
my friend wants to include. Among a lot of functions, there is a
function like void sort(int* arr), which he thinks that he could
implement better (and of course call it with the same name).
Such problems are beyond the scope of C++. They are more related to source control versioning systems like Git. If, for example, your project is under Git control, then your friend could create a branch of the code with his better implementation.
It is not possible at language level, aside from one "bizarre" language feature you mentioned yourself: replaceable operator new and operator delete functions. These functions can be replaced through a dedicated mechanism, which is why it is formally referred to as replacement (as opposed to overriding or overloading). This feature is not available to the language user for their own functions.
Outside the limits of standard language you can employ such implementation-specific features as weak symbols, which would allow you to create replaceable functions. For example, virtually all functions in GNU standard C library are declared as weak symbols and can be replaced with user-provided implementations.
The latter is exactly what would facilitate replacement of void sort(int* arr) function in your library. However this does not look like a good design for a library. Function replacement capability should probably reserved for debugging/logging and for other internal library-tuning purposes.

Can a namespace (be a/satisfy a) Concept?

I know the C++ Concepts proposal is intended, perhaps among other things, to place restrictions on template parameters (say, being a "Sequence"), over the current situation in which whatever manages to compile is good enough (and the error messages are abysmal).
But - what about namespaces? I mean, currently, we can't use them as template parameters, but one would think that if a method only uses the static methods and members of a class, then a namespace should also be a satisfactory thing to pass to it. Does the current version of / current implements of the Concepts proposal support that? If not, was this considered and rejected or just not considered?
Related question:
Is a class with only static methods better than a namespace with only non-member functions?
Concepts adds no mechanism to pass namespaces at compile or run time. So there is no way to test a namesoace against a conceot, or parametarize code with a namespace, barring macros.
The reflection TS may permit reflection over namespaces (I am not up to date on its current status), but that is orthogonal to concepts. Maybe reification and reflection of namespaces can be manipulated to permit concept checking of namespaces and passimg them around somehow, but if it does today it might not tomorrow and vice vers as it relies on two different plastic features where such a side effect would be accidental at best.

Regarding the global namespace in C++

In C++, should we be prepending stuff in the global namespace with ::?
For example, when using WinAPI, which is in C, should I do ::HANDLE instead of HANDLE, and ::LoadLibrary instead of LoadLibrary? What does C++ say about this? Is it generally a good idea, factoring in issues like readability and maintainability?
Names in C++ can be qualified and unqualified. There are different rules for qualified and unqualified name lookup. ::HANDLE is a qualified name, whereas HANDLE is an unqualified name. Consider the following example:
#include <windows.h>
int main()
{
int HANDLE;
HANDLE x; //ERROR HANDLE IS NOT A TYPE
::HANDLE y; //OK, qualified name lookup finds the global HANDLE
}
I think that the desicion of choosing HANDLE vs. ::HANDLE is a matter of coding style. Of course, as my example suggests, there might be situations where qualifying is mandatory. So, you might as well use :: just in case, unless the syntax is somewhat disgusting for you.
As namespaces don't exists in C, don't use ::HANDLE to access HANDLE type.
Using the prepending :: for global namespace is a good idea for readability, you know the type you want to access is from global namespace.
Moreover, if you are in a nested namespace and declare your own HANDLE type (for example), then the compiler will use this one instead of windows.h one!
Thus, always prefer using :: before names when working in nested namespace.
The main point of interest is what the differences are from the point of view of the compiler, as it has already been said, if you include the :: then you are using qualified lookup, rather than unqualified lookup.
The advantage of using qualified lookup is that it will be able to pinpoint a particular symbol always. The disadvantage is that it will always pinpoint that particular symbol --i.e. it will disable Argument Dependent Lookup. ADL is a big and useful part of the language, and by qualifying you effectively disable it, and that is bad.
Consider that you had a function f in the global namespace, and that you added a type T inside namespace N. Not consider that you wanted to add an overload of f that would take a T as argument. Following the interface principle, you can add f to the N namespace, as f is actually an operation performed on T, and it so belongs with the type. In this case, if you had code that called (consider generic code) ::f(obj) on an object of unknown type U the compiler will not be able to pick up ::N::f(obj) as a potential overload as the code is explicitly asking for an overload in the global namespace.
Using unqualified lookup gives you the freedom of defining the functions where they belong, together with the types that are used as arguments. While it is not exactly the same, consider the use of swap, if you qualify std::swap then it will not pick up your hand rolled void swap( T&, T& ) inside your N namespace...
I would only fully qualify identifiers when the compiler would otherwise not pick up the element I want.
It's largely a matter of style; there are no performance or efficiency concerns to speak of. It can be a good practice on large projects and projects intended to be compiled on many different platforms, as under these circumstances collisions between global names and names in a namespace are more likely to occur.
Normally, you do not have to prepend :: for the global namespace. (Only in some really rare circumstances). IMHO it harms readability, but, on the other hand it probably won't break your code
I put all of my code into a namespace, and I tend to prefer the C++ headers over the C headers, so the only symbols left in the global namespace tend to be from the Windows API. I avoid pulling symbols from other namespaces into the current namespace (e.g., I never have using namespace std;), preferring instead to qualify things explicitly. This is in line with Google's C++ style guide.
I've therefore gotten into the habit of qualifying WinAPI function calls with :: for a few reasons:
Consistency. For everything outside the current namespace, I refer to it explicitly (e.g., std::string), so why not refer to the Windows APIs explicitly (e.g., ::LoadLibraryW)? The Windows APIs namespace is the global namespace.
A lot of the WinAPI functions are named generically (e.g., DeleteObject). Unless you're very familiar with the code you're reading, you may not know whether DeleteObject is a call to something in the current namespace or to the Windows API. Thus, I find the :: clarifies.
A lot of Windows frameworks have methods with the same names as the raw calls. For example, ATL::CWindow has a GetClientRect method with a slightly different signature than WinAPI's GetClientRect. In this framework, it's common for your class to be derived from ATL::CWindow, so, in your class's implementation, it's normal to say GetClientRect to invoke the inherited ATL method and ::GetClientRect if you need to call the WinAPI function. It's not strictly necessary, since the compiler will find the right one based on the signature. Nevertheless, I find that the distinction clarifies for the reader.
(I know the question wasn't really about WinAPI, but the example was in terms of WinAPI.)
No, if you do not have a LoadLibrary method in your class you do not need to use the global scope. In fact, you should not use global scope because if you later on add a LoadLibrary to your class your intentions is probably to override the global function...

Should every class have its own namespace?

Something that has been troubling me for a while:
The current wisdom is that types should be kept in a namespace that only
contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions.
Does this imply that all classes must have a namespace of their own? If
we assume that a class may be augmented in the future by the addition of
non-member functions, then it can never be safe to put two types in the
same namespace as either one of them may introduce non-member functions
that could interfere with the other.
The reason I ask is that namespaces are becoming cumbersome for me. I'm
writing a header-only library and I find myself using classes names such as
project::component::class_name::class_name. Their implementations call
helper functions but as these can't be in the same namespace they also have
to be fully qualified!
Edit:
Several answers have suggested that C++ namespaces are simply a mechanism for avoiding name clashes. This is not so. In C++ functions that take a parameter are resolved using Argument Dependent Lookup. This means that when the compiler tries to find a function definition that matches the function name it will look at every function in the same namespace(s) as the type(s) of its parameter(s) when finding candidates.
This can have unintended, unpleasant consequences as detailed in A Modest Proposal: Fixing ADL. Sutter and Alexandrescu's rule states never put a function in the same namespace as a class unless it is meant to be part of the interface of that class. I don't see how I can obey that rule unless I'm prepared to give every class its own namespace.
More suggestions very welcome!
No. I have never heard that convention. Usually each library has its own namespace, and if that library has multiple different modules (e.g. different logical units that differ in functionality), then those might have their own namespace, although one namespace per library is sufficient. Within the library or module namespace, you might use namespace detail or an anonymous namespace to store implementation details. Using one namespace per class is, IMHO, complete overkill. I would definitely shy away from that. At the same time, I would strongly to urge you to have at least one namespace for your library and put everything within that one namespace or a sub-namespace thereof to avoid name clashes with other libraries.
To make this more concrete, allow me to use the venerable Boost C++ Libraries as an example. All of the elements within boost reside in boost::. There are some modules within Boost, such as the interprocess library that have its own namespace such as boost::interprocess::, but for the most part, elements of boost (especially those used very frequently and across modules) simply reside in boost::. If you look within boost, it frequently uses boost::detail or boost::name_of_module::detail for storing implementation details for the given namespace. I suggest you model your namespaces in that way.
No, no and a thousand times no! Namespaces in C++ are not architectural or design elements. They are simply a mechanism for preventing name clashes. If in practice you don't have name clashes, you don't need namespaces.
To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace.
Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still quite unlikely that you'd actually need a separate namespace per class to avoid ADL collisions.
Probably not. See Eric Lippert's post on the subject.
Couple things here:
Eric Lippert is a C# designer, but what he's saying about bad hierarchical design applies here.
A lot of what is being described in that article has to do with naming your class the same thing as a namespace in C#, but many of the same pitfalls apply to C++.
You can save on some of the typedef pain by using typedefs but that's of course only a band-aid.
It's quite an interesting paper, but then given the authors there was a good chance it would be. However, I note that the problem concerns mostly:
typedef, because they only introduce an alias and not a new type
templates
If I do:
namespace foo
{
class Bar;
void copy(const Bar&, Bar&, std::string);
}
And invoke it:
#include <algorithms>
#include "foo/bar.h"
int main(int argc, char* argv[])
{
Bar source; Bar dest;
std::string parameter;
copy(source, dest, parameter);
}
Then it should pick foo::copy. In fact it will consider both foo::copy and std::copy but foo::copy not being template will be given priority.