I come from a c# background where everything has its own namespace, but this practice appears to be uncommon in the c++ world. Should I wrap my code in it's own namespace, the unnamed namespace, or no namespace?
Many C++ developers do not use namespaces, sadly. When I started with C++, I didn't use them for a long time, until I came to the conclusion that I can do better using namespaces.
Many libraries work around namespaces by putting prefixes before names. For example, wxWidgets puts the characters "wx" before everything. Qt puts "Q" before everything. It's nothing really wrong with that, but it requires you to type that prefix all over again, even though when it can be deduced from the context which declarations you mean. Namespaces have a hierarchic order. Names that are lexically closer to the point that reference them are found earlier. So if you reference "Window" within your GUI framework, it will find "my::gui::Window", instead of "::Window".
Namespaces enable some nice features that can't be used without them. For example, if you put your class into a namespace, you can define free functions within that namespace. You then call the function without putting the namespace in front by importing all names, or selectively only some of them into the current scope ("using declaration").
Nowadays, I don't do any project anymore without using them. They make it so easy not to type the same prefix all over again, but still have good organization and avoidance of name-pollution of the global namespace.
Depends, if your code is library code, please wrap it in namespaces, that is the practice in C++. If your code is only a very simple application that doesn't interact with anything else, like a hello world sort of app, there is no need for namespaces, because its redundant.
And since namespaces aren't required the code snippets and examples on the web rarely use them but most real projects do use them.
I just discovered Google's c++ style guide and they have namespace guidelines.
The whole guide is worth reading, but to summarize, they say:
Add unnamed namespaces to .cc files, but not .h files.
Wrap entire (after includes/declarations) .cc and .h files in named namespaces.
Namespaces do not increment the indent level.
At the closing brace for a namespace write } // namespace.
Don't declare anything in std, because it is undefined.
using the using directive is forbidden.
the using declaration is allowed in functions, methods, and classes.
namespace aliases are allowed anywhere.
It really depends upon whether you expect there to be any conflicts.
Two scenarios;
1) If you are creating code that may be used by others (e.g libraries) then there could be namespace clashes so using your own namespace is a good idea.
2) If you are using third-party libraries their code may not be namespaced and could conflict with yours.
I would also say that if you expect your code to be sizable and cover many different areas (math/physics/rendering) then using namespaces does make the code easier to grok, particularly for types that are not obviously classified.
We had problems wrapping code in managed C++ that uses our common libraries here.
Some classes had the same names as System class in the .NET library (i.e. System.Console).
We had to do some ugly macro patches to workaround these problems.
Using namespaces at the beginning would have prevented this.
You only really need namespaces if there's a risk of names conflict - some globally seen function or variable or class is defined more than once. Otherwise you'll do just fine with no namespace - just name your classes so that they don't duplicate runtime library classes and make global functions/variable to be static members of some reasonable classes.
I'd say that it's a good idea, if for no other reason than to keep your stuff from getting stepped on when mixed with other third-party code.
I try to go even farther than that by putting as many variables and functions as I can into classes. But that's sometimes harder to do than it should be (compared to other OO languages).
but this practice appears to be
uncommon in the c++ world
Really. All the code I see seems to be wrapped in a namespace.
I use the same type of convention I see in Java (except I drop the com).
In Java
package com.<Company>.<Product>.<Package>;
In C++
namespace <Company>
{
namespace <Product>
{
namespace <Package>
{
}
}
}
Related
E.g. SFML::Render() vs SFML_Render()
I've noticed in libraries that offer C and C++ bindings, that often the C++ versions make use of namespaces (SFML, libtcod) and the C bindings do the same thing but just prefix the name with what library they belong to.
Both of them require the programmer to prefix the function, both give context as to where they belong, both of them perform the same function. I'm really confused as to what benefits namespaces offer over function prefixing.
using-declarations
You can write using SFML::Render after which you can simply call the function with Render(), without needing the SFML:: in the front. The using-declaration can also be scoped to a function or class. This is not possible with prefixed names.
using-directives
You can also bring a whole namespace to the current scope with using namespace. Everyone knows what using namespace std does. These can also be scoped.
Namespace aliases
If you have a symbol with a long qualified name e.g. mylib::sublib::foo::bar::x, you can write namespace baz = mylib::sublib::foo::bar and then refer to x with just baz::x. These are scope-specific as well.
Among the C-style prefixed names there's usually nothing that big that would need an alias, and if there were you could just use a macro.
Adding to & removing from a namespace
If you have a file full of functions that need to be placed under a namespace x you can simply add two lines to make it happen: namespace x { and }. Removing from a namespace is equally simple. With prefixed names you have to manually rename each function.
Argument-dependent lookup
You may be able to omit the namespace qualification on a function call if the function lives in the same namespace as some of its arguments. For example, if namespace baz contains both an enum E and a function F that takes it, you can write F(baz::E) instead of baz::F(baz::E). This can be handy if you follow the style that prefers namespaced free functions over methods.
So in conclusion, namespaces are more flexible and offer more possibilities than the prefixed naming style.
SFML_Render is easy to find with fgrep -w SFML_Render, whereas SFML::Render may appear in some source files as just Render if the SFML namespace is implicit.
If you program in C++, there are strong benefits in using the C++ constructs, but you better use a powerful environment such as Eclipse or Visual Studio to help you make sense of all the added complexities.
If you want interoperability with C, you should not use namespaces nor overloading.
they way i see it there are severel uses for namespaces.
some of them:
Name isolation: define a package (a set of classes, functions,
globals, type definitions, etc.) in a namespace to ensure that when
included, these names do not conflict with existing code.
Version control: maintain multiple versions of the code.
and offcourse : A using statement can be used to make names available
without the :: scope operator
Ideally, namespaces should
• Express a logical coherent set of features
• Prevent user access to unrelated features.
• Impose minimal notational burden on users.
Every once in a while, I stumble across some code that I'm maintaining that challenges the way I think about my code style. Today was one of those days...
I'm aware that about why you would want to use the scope operator to define global scope. In fact, here scope resolution operator without a scope is a great link tell you why.
However, I saw something that made me think today. All the classes in question were wrapped into a namespace for the project (good!), but I did see copious usage of the global scope operator. Namely, it was used for everything from C libraries (with the exception of uint8_t and the like... yes, the programmer used the .h version of this library since apparently the version of g++ they were running still threw warnings about the new C++ standard). Is this useful? I view this as just as a waste of characters (reminds me of using the this pointer... except in the case of the copy constructor and assignment operator where it helps in clarifying which object is which). Am I missing something? Sure, someone can come around and name something along the lines of usleep() or stderr (where I saw the most usage of "::"), but won't they know that doing so will probably break something horribly? At what point do you say "screw it" in terms of the scope operator and just tell yourself that someone who names a function a certain way within your namespace is asking for trouble?
So my question is... what is the "correct" (subjective I understand) way of using the global scope operator in this context? Should everything not included in std or your own namespaces have the global scope explicitly defined? I tend to err on the side of caution and use "std::" to avoid the using directive, but is anything gained from using the global scope operator here? I tend to think for clarity's sake it does lend to the fact that we aren't getting the variable or function in question from the current namespace, but I'm torn between including it and not given today's developments.
As always, thanks for the help and guidance as I look to make my code cleaner, more readable, and (of course) significantly more awesome.
I use it quite infrequently; only when some ambiguity needs resolving for whatever reason. This is pretty subjective, though.
There may be some occasions (say, inside a template) where you're worried about ADL causing ambiguities only in certain cases:
template <typename T>
void foo(T t)
{
::bar(t); // :: just in case there's a `bar` in `T`'s namespace
}
There is almost no correct answer to this as it's almost totally style related, with the exception that if you think you may want to change from where you are going to import some declaration(s)/definition(s), in which case, when you use them, you don't specify any scope and import them using the using directive (to import a subset from the namespace) or the using namespace directive to import the entire set from the namespace.
Mostly the using directive is used as a convenience directive, but it is a powerful way to direct which declarations/definitions are used. My preference is to not specify the scope and import the declarations. Doing this allows for easy changes if ever they are needed while reducing visual noise. Also, specifying the scope would mean I'd be "locked in" from where I am getting the declarations (well, I'd have to do a global search and replace to change it).
If ever there is a conflict (you try an use a declared item with the same name that has been imported from more than one namespace) the compiler will let you know, so there's no real danger.
Readable code is that has the least amount of noise. namespace prefixes normally provide nothing but noise. So baseline is to not have them at all.
Namespaces were introduced to C++ mainly to handle 3rd party stuff out of one's control. To allow libraries drop prefixing, while clients can use terse names by applying using.
Just because you can have the same name in many namespaces does not imply it is a good idea to too. If a project uses some environment, platform API, library set, whatever that puts name in global, those names are better be avoided for other purposes. As with or without prefixes they will bear mental overhead.
Use of :: is rare in well-shaped code, and frequent uses appear in wrapper classes for that same functionality.
Consider the following cases.
Public library.
You are writing an exportable library with public headers. And you absolutely have no clue in what environment your headers will be included. For example, someone may do:
namespace std = my_space::std;
#include "your_header"
And all your definitions will be corrupted, if you simply use: std::list<int>, etc. So, it's a good practice to prepend :: to everything global. This way you can be absolutely sure what you're using. Of course, you can do using (in C++11) or typedef - but it's a wrong way to go in headers.
Collaborative .cc/.cpp files.
Inside your own code that is not exposed to public in any way, but still editable not only by you - it's a good practice to announce, what you're going to use from outside of your namespace. Say, your project allows to use a number of vectors - not only an std::vector. Then, where it's appropriate, you put a using directive:
// some includes
using vector = ::std::vector<int>; // C++11
typedef ::std::vector<int> vector; // C++03
namespace my_namespace {
...
} // namespace my_namespace
It may be put after all includes, or inside specific functions. It's not only gives control over the code, but also makes it readable and shortens expressions.
Another common case - is a mixing of global C functions and a C++ code. It's not a good idea to do any typedefs with function names. In this situation you should prepend C functions with the global scope resolution operator :: - to avoid compilation problems, when someone implements a function with a same signature in the same namespace.
Don't use :: for relative types and namespaces - or you'll lose the benefit of using namespaces at all.
Your own code.
Do what you want and how you want. There is only one good way - the way you fill comfortable with your own code. Really, don't bother about global scope resolution in this situation, if it's not requiered to resolve an ambiguity.
I am a C++ newcomer, trying to learn the language in parallel as I work on a project that requires it. I am using a fairly popular and stable open source library to do a lot of heavy lifting. Reading through the source, tutorials and code samples for the library, I have noticed that they always use fully qualified names when declaring types, which often results in very long and verbose lines with lots of ::'s. Is this considered best practice in C++? Is there a different way to deal with this?
They may have found it easier than answering lots of questions from people who tried the example code and found it didn't work, just because they didn't "use" the namespaces involved.
Practices vary - if you're working on a large project with lots of diverse libraries and name clashes, you may wish to proactively use more namespace qualifiers consistently so that as you add new code you won't have to go and make old code more explicit about what it's trying to use.
Stylistically, some people prefer knowing exactly what's being referred to to potentially having to dig around or follow an IDE "go to declaration" feature (if available), while other people like concision and to see fuller namespace qualification only on the "exceptional" references to namespaces that haven't been included - a more contextual perspective.
It's also normal to avoid having "using namespace xxx;" in a header file, as client code including that header won't be able to turn it off, and the contents of that namespace will be permanently dumped into their default "search space". So, if you're looking at code in a header that's one reason they might be more explicit. Contrasting with that, you can having "using namespace" inside a scope such as a function body - even in a header - and it won't affect other code. It's more normal to use an namespace from within an implementation file that you expect to be the final file in a translation unit, compiling up to a library or object that you'll link into the final executable, or perhaps a translation unit that itself creates the executable.
First typedefs:
typedef std::vector<MyTypeWithLongName>::const_iterator MyTypeIt;
//use MyTypeIt from now on
Second "using"
using std::string;
//use string instead of std::string from now on
Third "using namespace"
using namespace std;
//Use all things from std-namespace without std:: in front (string, vector, sort etc.)
For the best practice: Don't use 'using' and 'using namespace' a lot. When you have to use it (sometimes keeps the code cleaner) never put it in the header but in the .cpp file.
I tend to use one of those above if the names get really long or I have to use the types a lot in the same file.
If you are writing your own libraries you will certainly have heavy use of namespaces, In your core application there should be fewer uses. As for doing something like std::string instead of starting with using namespace std; imo the first version is better because It is more descriptive and less prone to errors
I've easily gotten myself into the habit of prefixing standard identifiers with std:: instead of sticking in a using namespace std;. However, I've started getting into C# and I've noticed that it's very normal to add in whatever using directives are necessary, i.e., you'd see:
using System;
Console.Write("foo");
instead of:
System.Console.Write("foo");
Apparently, as I found out from a C# question on this topic, that usage comes from the fact that individual system namespaces in C# are much, much smaller than std is in C++, and therefore eliminates the problems associated with name clashes, as there is much less likelihood (and you can just find-replace it with a fully qualified name if a library updates with a name-clash), and eliminates the problems associated with a crapload of Intellisense options appearing, as the namespaces are small enough to handle.
The question, then, is that if these are the standing reasons to make use of using directives in C#, is the same true for C++? Is it generally acceptable to apply this to smaller third-party namespaces, as well as your own smaller namespaces?
Now I realize that this might cause a bit of controversy, I want to take this moment to ask that it doesn't turn into an argument. A good answer should include a basis, i.e., advantages or disadvantages, and how using one way over the other really makes a worthwhile difference.
The reason I ask this is to clear up the issue, and possibly remove the notion that using directives in C++ have to be a bad thing. Sure longer namespace names can be cut down with a namespace alias if necessary, and fully qualified names can still be used if needed, but sometimes a using directive greatly eases accessing some members such as user-defined literal operators, which, to my knowledge, have no form of ADL, meaning that you either have to use a using directive, or call the operator method by the function syntax, defeating the whole purpose of using the operator in the first place.
For example, I had a namespace (that includes a structure representing a keyboard key, along with a literal suffix as a readable alternate means of access:
"caps lock"_key.disable();
The problem here is that unless you have previously inserted using namespace Whatever; or using Whatever::operator"" _key;, the code won't compile, which is bad news for the user.
Using directives have obvious problems when std is involved or when used in such a way in a header that they bring unwanted extras for the user of that header, but is it justified to use them for other namespaces when contained within a smaller scope than whatever includes a header? The keystrokes saved from not having to type each qualifier each time do add up, and with today's Intellisense capabilities, finding out which namespace an unqualified identifier belongs to is as easy as mousing over it.
I think the rules about using declarations in C++ are rather simple:
NEVER write "using namespace anything;" in the global scope of a header, especially one that is likely to be reused by other programs (e.g. when writing a library). It pollutes the global scope of all subsequent headers with the symbols of this namespace, which defeats the entire purpose of namespaces, and can create unforeseen name clashes later on.
In the .cpp files and inner scopes of headers (e.g. inline function scopes), you can be "using" whatever namespaces you want, as it won't affect any other file. Just do whatever is more convenient for you and try to be reasonably consistent within a project.
EDIT: for the _key problem, simply define this operator in its own namespace and tell users to import it. This way they won't need to type out the operator declaration.
namespace something {
class key { ... };
}
namespace key_suffix {
something::key operator"" _key() { ... }
}
// user code
void some_function() {
using namespace key_suffix;
"caps lock"_key.doSomething();
}
Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like using namespace x in C++, or from x import * in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.
For example:
import foo # Contains someFunction().
someFunction() # imported from foo. No ambiguity. Works.
Vs.
import foo # Contains someFunction()
import bar # Contains someFunction() also.
# foo.someFunction or bar.someFunction? Should be an error only because
# ambiguity exists.
someFunction()
One reason is to protect against accidentally introducing a conflict when you change the code (or for an external module/library, when someone else changes it) later on. For example, in Python you can write
from foo import *
from bar import *
without conflicts if you know that modules foo and bar don't have any variables with the same names. But what if in later versions both foo and bar include variables named rofl? Then bar.rofl will cover up foo.rofl without you knowing about it.
I also like to be able to look up to the top of the file and see exactly what names are being imported and where they're coming from (I'm talking about Python, of course, but the same reasoning could apply for C++).
Python takes the view that 'explicit is better than implicit'.
(type import this into a python interpreter)
Also, say I'm reading someone's code. Perhaps it's your code; perhaps it's my code from six months ago. I see a reference to bar(). Where did the function come from? I could look through the file for a def bar(), but if I don't find it, what then? If python is automatically finding the first bar() available through an import, then I have to search through each file imported to find it. What a pain! And what if the function-finding recurses through the import heirarchy?
I'd rather see zomg.bar(); that tells me where the function is from, and ensures I always get the same one if code changes (unless I change the zomg module).
The problem is about abstraction and reuse : you don't really know if there will not be any future ambiguity.
For example, It's very common to setup different libraries in a project just to discover that they all have their own string class implementation, called "string".
You compiler will then complain that there is ambiguity if the libraries are not encapsulated in separate namespaces.
It's then a delightful pleasure to dodge this kind of ambiguity by specifying wich implementation (like the standard std::string one) you wants to use at each specific instruction or context (read : scope).
And if you think that it's obvious in a particular context (read : in a particular function or .cpp in c++, .py file in python - NEVER in C++ header files) you just have to express yourself and say that "it should be obvious", adding the "using namespace" instruction (or import *). Until the compiler complain because it is not.
If you use using in specific scopes, you don't break the DRY rule at all.
There have been languages where the compiler tried to "do the right thing" - Algol and PL/I come to mind. The reason they are not around anymore is that compilers are very bad at doing the right thing, but very good at doing the wrong one, given half a chance!
The ideal this rule strives for is to make creating reusable components easy - and if you reuse your component, you just don't know which symbols will be defined in other namespaces the client uses. So the rule forces you to make your intention clear with respect to further definitions you don't know about yet.
However, this ideal has not been reached for C++, mainly because of Koenig lookup.
Is it really the right thing?
What if I have two types ::bat and ::foo::bar
I want to reference the bat type but accidentally hit the r key instead of t (they're right next to each others).
Is it "the right thing" for the compiler to then go searching through every namespace to find ::foo::bar without giving me even a warning?
Or what if I use "bar" as shorthand for the "::foo::bar" type all over my codebase.
Then one day I include a library which defines a ::bar datatype. Suddenly an ambiguity exists where there was none before. And suddenly, "the right thing" has become wrong.
The right thing for the compiler to do in this case would be to assume I meant the type I actually wrote. If I write bar with no namespace prefix, it should assume I'm referring to a type bar in the global namespace. But if it does that in our hypothetical scenario, it'll change what type my code references without even alerting me.
Alternatively, it could give me an error, but come on, that'd just be ridiculous, because even with the current language rules, there should be no ambiguity here, since one of the types is hidden away in a namespace I didn't specify, so it shouldn't be considered.
Another problem is that the compiler may not know what other types exist. In C++, the order of definitions matters.
In C#, types can be defined in separate assemblies, and referenced in your code. How does the compiler know that another type with the same name doesn't exist in another assembly, just in a different namespace? How does it know that one won't be added to another assembly later on?
The right thing is to do what gives the programmer the fewest nasty surprises. Second-guessing the programmer based on incomplete data is generally not the right thing to do.
Most languages give you several tools to avoid having to specify the namespace.
In c++, you have "using namespace foo", as well as typedefs. If you don't want to repeat the namespace prefix, then don't. Use the tools made available by the language so you don't have to.
This all depends on your definition of "right thing". Is it the right thing for the compiler to guess your intention if there's only one match?
There are arguments for both sides.
Interesting question. In the case of C++, as I see it, provided the compiler flagged an error as soon as there was a conflict, the only problem this could cause would be:
Auto-lookup of all C++ namespaces would remove the ability to hide the names of internal parts of library code.
Library code often contains parts (types, functions, global variables) that are never intended to be visible to the "outside world." C++ has unnamed namespaces for exactly this reason -- to avoid "internal parts" clogging up the global namespace, even when those library namespaces are explicitly imported with using namespace xyz;.
Example: Suppose C++ did do auto-lookup, and a particular implementation of the C++ Standard Library contained an internal helper function, std::helper_func(). Suppose a user Joe develops an application containing a function joe::helper_func() using a different library implementation that does not contain std::helper_func(), and calls his own method using unqualified calls to helper_func(). Now Joe's code will compile fine in his environment, but any other user who tries to compile that code using the first library implementation will hit compiler error messages. So the first thing required to make Joe's code portable is to either insert the appropriate using declarations/directives or use fully qualified identifiers. In other words, auto-lookup buys nothing for portable code.
Admittedly, this doesn't seem like a problem that's likely to come up very often. But since typing explicit using declarations/directives (e.g. using namespace std;) is not a big deal for most people, solves this problem completely, and would be required for portable development anyway, using them (heh) seems like a sensible way to do things.
NOTE: As Klaim pointed out, you would never in any circumstances want to rely on auto-lookup inside a header file, as this would immediately prevent your module from being used at the same time as any module containing a conflicting name. (This is just a logical extension of why you don't do using namespace xyz; inside headers in C++ as it stands.)