There are convincing arguments against using namespace std, so why was it introduced into the language at all? Doesn't using namespace defeat the purpose of namespaces? Why would I ever want to write using namespace? Is there any problem I am not aware of that is solved elegantly by using namespace, maybe in the lines of the using std::swap idiom or something like that?
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops; or using namespace boost::assign;)
Brevity is also a strong argument. Would you really enjoy typing and reading std::placeholders::_1 instead of _1? Also, when you write code in functional style, you'll be using a myriad of objects in std and boost namespace.
Another important usage (although normally one doesn't import whole namespaces) is to enable argument-dependent look-up:
template <class T>
void smart_swap(T& a, T& b)
{
using std::swap;
swap(a, b);
}
If swap is overloaded for some type of T in the same namespace as T, this will use that overload. If you explicitly called std::swap instead, that overload would not be considered. For other types this falls back to std::swap.
BTW, a using declaration/directive does not defeat the purpose of namespaces, since you can always fully qualify the name in case of ambiguity.
Most of the times it is just a shortcut for writing code. You can import names into your enclosing context. I usually restrict it to .cpp files, because when you include an using directive into a .h file, it pollutes all the files in which it is included. Another good practice is restricting the using namespace to the most enclosing environment possible, for instance, inside of a method body declaration. I see it as a convenience, no more, and similar to namespace aliasing, such as:
namespace po = boost::program_options;
and then you can write
po::variables_map ...
The main reason why using namespace was introduced was backwards compatibility: If you have lots of pre-namespace code using lots of (pre-standard versions of) standard library functions and classes, you want a simple way to make that code work with a standard conforming compiler.
BTW, the argument dependent lookup rules at least for C++98 mean that using namespace std::rel_ops will not do what you want in templates (I don't know if this changed in a later version of the standard).
Example:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
}
using namespace std::rel_ops;
int main()
{
X x;
bar(x); // won't work: X does not have operator>
}
Note that putting the using namespace in namespace foo won't help either.
However, using declarations in the right spot help:
template<typename T> bool bar(T t)
{
return t > T();
}
namespace foo
{
class X {};
bool operator<(X, X);
using std::rel_ops::operator>;
}
int main()
{
X x;
bar(x); // now works: operator> found per ADL via the using declaration in `namespace foo`
}
People specifically object to using namespace std; but not to using namespace BigCorp; or to referring to std::cout (which is using the namespace, just not using it, if you know what I mean.) Also, most of the objections to using namespace std are in a header file. In a source file, where the effects can be immediately seen, it's less harmful.
Namespaces are an incredibly useful concept that allow me to have a class called Date even though a library I'm using has a class called Date. Before they were added to the language, we had to have things like GCDate and GCString (my company, Gregory Consulting, predates std::string). Making use of namespaces (with or without the using keyword) lets us all write cleaner, neater code. But when you have to say Gregcons::string every time, you kind of lose the cleaner, neater part. [Disclaimer: I don't actually use my own string class anymore - imagine some appropriate name conflict.] That's the appeal of the using statement. Keep it out of headers, don't apply it to std, and you should generally stay out of trouble.
I find it useful when working with libraries with deeply nested namespaces. The Boost library is one such example. Imaging typing boost::numeric::ublas::matrix<double> m all over the place ...
The thing to avoid is doing using namespace in a header file as this has the potential for royally screwing up any program that includes said header. Always place using namespace statements in .cpp/.cxx files, so that it's restricted to file scope.
"Namespaces allow to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name. Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace"
More information here:
http://www.cplusplus.com/doc/tutorial/namespaces/
Related
In C++ Primer, there is one tips says:
One place where using directives are useful is in the implementation
files for the namespace itself.
I guess this is just for using shorthand names? I am not sure how it is different from just surrounding the implementation with
namespace namespace_name
{
}
Thanks.
That applies to modifications to your own namespaces. The purpose of using directives is to import symbols from a different namespace. For example, an infamous idiom:
namespace my_stuff
{
template <typename Container>
void my_fn( Container& xs )
{
using std::begin;
using std::end;
std::sort( begin(xs), end(xs) );
}
}
Everything happens in your my_namespace, but it makes available the std::begin() and std::end() functions if needed. If a more local definition for begin() and end() exists that better matches the Container type, then it will be used instead. If you had simply wrapped everything in the std namespace, this useful ability would be lost.
Hope this helps.
I am not sure how it is different from just surrounding the implementation with namespace namespace_name { }
This is to put your own code within a namespace, as opposed to using some name from another namespace. Say you write a draw function inside the Graphics namespace -- to do this, you wrap draw's code in namespace Math { void draw() { /* some code */ } } and to use it you'd do Graphics::draw. However, when you need to use a function, say, gamma in the Math namespace (which you didn't write), you've to call it Math::gamma for the compiler to know where to search for gamma. Alternatively, you may use shorthand, to drop the Math:: part.
I guess this is just for using shorthand names?
Yes, that's to allow identifiers from some namespace to be used without the qualifier. There are two ways to do it.
Using directive: Use all names in a namespace without qualification (e.g. using namespace Math;)
Using declaration: Use only some specified names without qualification (e.g. using Math::gamma) -- this is usually better than the former.
However, both are encouraged to be used only in an implementation/source file and not in a header to avoid some sources which may have its own copy of gamma and don't want to use Math::gamma, but since you've it in the header, it'll lead a clash of the names. More details on "using namespace" in c++ headers.
This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 7 years ago.
Two ways to use the using declaration are
using std::string;
using std::vector;
or
using namespace std;
which way is better?
It depends.
If you want to inject a single name into another scope, the using-declaration is better, e.g.
namespace foolib
{
// allow vector to be used unqualified within foo,
// or used as foo::vector
using std::vector;
vector<int> vec();
template<typename T> struct Bar { T t; };
template<typename T>
void swap(Bar<T>& lhs, Bar<T>& rhs)
{
using std::swap;
// find swap by ADL, otherwise use std::swap
swap(lhs.t, rhs.t);
}
}
But sometimes you just want all names, which is what a using-directive does. That could be used locally in a function, or globally in a source file.
Putting using namespace outside a function body should only be done where you know exactly what's being included so it's safe (i.e. not in a header, where you don't know what's going to be included before or after that header) although many people still frown on this usage (read the answers at Why is "using namespace std" considered bad practice? for details):
#include <vector>
#include <iostream>
#include "foolib.h"
using namespace foo; // only AFTER all headers
Bar<int> b;
A good reason to use a using-directive is where the namespace only contains a small number of names that are kept intentionally segregated, and are designed to be used by using-directive:
#include <string>
// make user-defined literals usable without qualification,
// without bringing in everything else in namespace std.
using namespace std::string_literals;
auto s = "Hello, world!"s;
So there is no single answer that can say one is universally better than the other, they have different uses and each is better in different contexts.
Regarding the first usage of using namespace, the creator of C++, Bjarne Stroustrup, has this to say in ยง14.2.3 of The C++ Programming Language, 4th Ed (emphasis mine):
Often we like to use every name from a namespace without qualification. That can be achieved by providing a using-declaration for each name from the namespace, but that's tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use a using-directive to request that every name from a namespace be accessible in our scope without qualification. [...]
[...] Using a using-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book. [...]
Within a function, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid. [...]
Consequently, we must be careful with using-directives in the global scope. In particular, don't place a using-directive in the global scope in a header file except in very specialized circumstances (e.g. to aid transition) because you never know where a header might be #included.
To me this seems far better advice than just insisting it is bad and should not be used.
using std::string; and using std::vector;.
Polluting the global namespace with a bunch of symbols is a bad idea. You should just use the std namespace prefix too, so you know that you're using standard library containers. Which is better than both options IMO.
If you are simply using the standard library and nothing else and never will be adding in any other libraries to your project, by all means, use using namespace std; - Whatever you feel more comfortable with in that situation. The convention of "never use using namespace std;" comes from the fact that multiple other libraries define things such as string, vector and such. It is good practice to never import the whole namespace, but it should cause no bothers in your case.
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
Then in code:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked below, you can use as many namespaces as you like.
To avoid saying everything Mark Ingram already said a little tip for using namespaces:
Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.
I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.
Sometimes namespaces are used in bigger C++ projects to hide implementation details.
Additional note to the using directive:
Some people prefer using "using" just for single elements:
using std::cout;
using std::endl;
I did not see any mention of it in the other answers, so here are my 2 Canadian cents:
On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;
you can write:
namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;
Vincent Robert is right in his comment How do you properly use namespaces in C++?.
Using namespace
Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the "org.domain" idiom (because it is supposed one won't use anything else than his/her own domain name).
In C++, you could give a namespace to all the code in your module. For example, for a module MyModule.dll, you could give its code the namespace MyModule. I've see elsewhere someone using MyCompany::MyProject::MyModule. I guess this is overkill, but all in all, it seems correct to me.
Using "using"
Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.
This is evil to do it in a header file because your header will pollute every source including it (it reminds me of macros...), and even in a source file, bad style outside a function scope because it will import at global scope the symbols from the namespace.
The most secure way to use "using" is to import select symbols:
void doSomething()
{
using std::string ; // string is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
std::cout << a << std::endl ;
}
void doSomethingElse()
{
using namespace std ; // everything from std is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
cout << a << endl ;
}
You'll see a lot of "using namespace std ;" in tutorial or example codes. The reason is to reduce the number of symbols to make the reading easier, not because it is a good idea.
"using namespace std ;" is discouraged by Scott Meyers (I don't remember exactly which book, but I can find it if necessary).
Namespace Composition
Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".
In the "Special Edition", at 8.2.8 Namespace Composition, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:
namespace AAA
{
void doSomething() ;
}
namespace BBB
{
void doSomethingElse() ;
}
namespace CCC
{
using namespace AAA ;
using namespace BBB ;
}
void doSomethingAgain()
{
CCC::doSomething() ;
CCC::doSomethingElse() ;
}
You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.
Don't listen to every people telling you that namespaces are just name-spaces.
They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:
namespace ns {
class A
{
};
void print(A a)
{
}
}
If you wanted to print an A object, the code would be this one:
ns::A a;
print(a);
Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.
Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.
namespace ns {
class A
{
};
}
void print(A a)
{
}
And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.
Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.
And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.
If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter
Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).
Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.
Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.
Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:
namespace {
const int CONSTANT = 42;
}
This is basically the same as:
static const int CONSTANT = 42;
Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.
Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:
namespace MyNamespace
{
double square(double x) { return x * x; }
}
in a file square.h, and
namespace MyNamespace
{
double cube(double x) { return x * x * x; }
}
in a file cube.h. This defines a single namespace MyNamespace (that is, you can define a single namespace across multiple files).
In Java:
package somepackage;
class SomeClass {}
In C++:
namespace somenamespace {
class SomeClass {}
}
And using them, Java:
import somepackage;
And C++:
using namespace somenamespace;
Also, full names are "somepackge.SomeClass" for Java and "somenamespace::SomeClass" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren't there though, so you can name your folders and classes independently off packages and namespaces.
#marius
Yes, you can use several namespaces at a time, eg:
using namespace boost;
using namespace std;
shared_ptr<int> p(new int(1)); // shared_ptr belongs to boost
cout << "cout belongs to std::" << endl; // cout and endl are in std
[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.
Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala boost:: .
I prefer using a top-level namespace for the application and sub namespaces for the components.
The way you can use classes from other namespaces is surprisingly very similar to the way in java.
You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.
I've used C++ namespaces the same way I do in C#, Perl, etc. It's just a semantic separation of symbols between standard library stuff, third party stuff, and my own code. I would place my own app in one namespace, then a reusable library component in another namespace for separation.
Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:
#include "lib/module1.h"
#include "lib/module2.h"
lib::class1 *v = new lib::class1();
I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.
std :: cout
The
prefix std:: indicates that the
names cout and endl are
defined inside the namespace
named std. Namespaces allow
us to avoidinadvertent collisions
between the names we define
and uses of those same names
inside a library. All the names
defined by the standard library
are in the stdnamespace. Writing std::
cout uses the scope operator
(the ::operator) to saythat we
want to use the name cout
that is defined in the
namespace std.
will show a simpler way to
access names from the library.
In the stlport library, I saw this code:
namespace std { }
namespace __std_alias = std;
1. Are they trying to nullify the standard std namespace in the first line?
2. Why in the world would they use a longer alias name in place of the original name?
You need the namespace "in scope" before you can declare an alias to it. The empty namespace std {} informs the compiler that the namespace exists. Then they can create an alias to it.
There are reasons for creating aliases besides creating a shortcut. For example, you can define a macro to "rename" the namespace -- consider the effect of #define std STLPORT_std. Having a alias allows you to access the original namespace provided that you play the correct ordering games with header files.
No, that just makes sure the namespace's name is available in the current scope. You can open and close namespaces at any point, without affecting the contents of the namespace.
I would guess, so they could easily change their library implementation to be in a namespace other than ::std (by changing __std_alias to alias something else). This would be useful, for example, if you want to test two implementations alongside each other.
It is rather annoying to get a compiler error that there is no such namespace as std... What is the compiler thinking? Of course it exists!
Well yes it does, but as with library features, it has to be declared first. That is what the first line is doing.
With the renaming of __std_alias it allows them to give a new alias to a namespace. You may decide to do this in your own code someday.
Perhaps you want to use shared_ptr in your code but do not want to dedicate your code to using namespace boost or std. So you can create an alias, and "point" it at either boost or std. Same with other features that are in boost libraries that later became standard.
This does not tie you to using this namespace for everything as you can have more than one alias, and you can have more than one pointing to the same real namespace.
Let's say we want to call our smart pointer library sml. We can do
namespace sml = boost; // or std
in one place in the code and #include <boost/shared_ptr.hpp> from that point in the code (same header).
Everywhere else in our code we use sml::shared_ptr. If we ever switch from boost to std, just change the one header, not all your code.
In addition to what D.Shawley said, forward declaring a class that's inside a namespace requires the same syntax:
namespace std
{
template <typename T>
class vector;
}
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this:
namespace MyNamespace
{
class MyClass
{
};
}
Then in code:
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
Or, if you want to always use a specific namespace, you can do this:
using namespace MyNamespace;
MyClass* pClass = new MyClass();
Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked below, you can use as many namespaces as you like.
To avoid saying everything Mark Ingram already said a little tip for using namespaces:
Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.
I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.
Sometimes namespaces are used in bigger C++ projects to hide implementation details.
Additional note to the using directive:
Some people prefer using "using" just for single elements:
using std::cout;
using std::endl;
I did not see any mention of it in the other answers, so here are my 2 Canadian cents:
On the "using namespace" topic, a useful statement is the namespace alias, allowing you to "rename" a namespace, normally to give it a shorter name. For example, instead of:
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::TheClassName foo;
Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally::AnotherClassName bar;
you can write:
namespace Shorter = Some::Impossibly::Annoyingly::Long:Name::For::Namespace::Finally;
Shorter::TheClassName foo;
Shorter::AnotherClassName bar;
Vincent Robert is right in his comment How do you properly use namespaces in C++?.
Using namespace
Namespaces are used at the very least to help avoid name collision. In Java, this is enforced through the "org.domain" idiom (because it is supposed one won't use anything else than his/her own domain name).
In C++, you could give a namespace to all the code in your module. For example, for a module MyModule.dll, you could give its code the namespace MyModule. I've see elsewhere someone using MyCompany::MyProject::MyModule. I guess this is overkill, but all in all, it seems correct to me.
Using "using"
Using should be used with great care because it effectively import one (or all) symbols from a namespace into your current namespace.
This is evil to do it in a header file because your header will pollute every source including it (it reminds me of macros...), and even in a source file, bad style outside a function scope because it will import at global scope the symbols from the namespace.
The most secure way to use "using" is to import select symbols:
void doSomething()
{
using std::string ; // string is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
std::cout << a << std::endl ;
}
void doSomethingElse()
{
using namespace std ; // everything from std is now "imported", at least,
// until the end of the function
string a("Hello World!") ;
cout << a << endl ;
}
You'll see a lot of "using namespace std ;" in tutorial or example codes. The reason is to reduce the number of symbols to make the reading easier, not because it is a good idea.
"using namespace std ;" is discouraged by Scott Meyers (I don't remember exactly which book, but I can find it if necessary).
Namespace Composition
Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's "The C++ Programming Language".
In the "Special Edition", at 8.2.8 Namespace Composition, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:
namespace AAA
{
void doSomething() ;
}
namespace BBB
{
void doSomethingElse() ;
}
namespace CCC
{
using namespace AAA ;
using namespace BBB ;
}
void doSomethingAgain()
{
CCC::doSomething() ;
CCC::doSomethingElse() ;
}
You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.
Don't listen to every people telling you that namespaces are just name-spaces.
They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:
namespace ns {
class A
{
};
void print(A a)
{
}
}
If you wanted to print an A object, the code would be this one:
ns::A a;
print(a);
Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.
Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.
namespace ns {
class A
{
};
}
void print(A a)
{
}
And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.
Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.
And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.
If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter
Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).
Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.
Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.
Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:
namespace {
const int CONSTANT = 42;
}
This is basically the same as:
static const int CONSTANT = 42;
Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.
Also, note that you can add to a namespace. This is clearer with an example, what I mean is that you can have:
namespace MyNamespace
{
double square(double x) { return x * x; }
}
in a file square.h, and
namespace MyNamespace
{
double cube(double x) { return x * x * x; }
}
in a file cube.h. This defines a single namespace MyNamespace (that is, you can define a single namespace across multiple files).
In Java:
package somepackage;
class SomeClass {}
In C++:
namespace somenamespace {
class SomeClass {}
}
And using them, Java:
import somepackage;
And C++:
using namespace somenamespace;
Also, full names are "somepackge.SomeClass" for Java and "somenamespace::SomeClass" for C++. Using those conventions, you can organize like you are used to in Java, including making matching folder names for namespaces. The folder->package and file->class requirements aren't there though, so you can name your folders and classes independently off packages and namespaces.
#marius
Yes, you can use several namespaces at a time, eg:
using namespace boost;
using namespace std;
shared_ptr<int> p(new int(1)); // shared_ptr belongs to boost
cout << "cout belongs to std::" << endl; // cout and endl are in std
[Feb. 2014 -- (Has it really been that long?): This particular example is now ambiguous, as Joey points out below. Boost and std:: now each have a shared_ptr.]
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.
Generally speaking, I create a namespace for a body of code if I believe there might possibly be function or type name conflicts with other libraries. It also helps to brand code, ala boost:: .
I prefer using a top-level namespace for the application and sub namespaces for the components.
The way you can use classes from other namespaces is surprisingly very similar to the way in java.
You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.
I've used C++ namespaces the same way I do in C#, Perl, etc. It's just a semantic separation of symbols between standard library stuff, third party stuff, and my own code. I would place my own app in one namespace, then a reusable library component in another namespace for separation.
Another difference between java and C++, is that in C++, the namespace hierarchy does not need to mach the filesystem layout. So I tend to put an entire reusable library in a single namespace, and subsystems within the library in subdirectories:
#include "lib/module1.h"
#include "lib/module2.h"
lib::class1 *v = new lib::class1();
I would only put the subsystems in nested namespaces if there was a possibility of a name conflict.
std :: cout
The
prefix std:: indicates that the
names cout and endl are
defined inside the namespace
named std. Namespaces allow
us to avoidinadvertent collisions
between the names we define
and uses of those same names
inside a library. All the names
defined by the standard library
are in the stdnamespace. Writing std::
cout uses the scope operator
(the ::operator) to saythat we
want to use the name cout
that is defined in the
namespace std.
will show a simpler way to
access names from the library.