using std::<type> v.s. using std namespace [duplicate] - c++

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.

Related

using standard namespace in C plus plus

Consider this
#include<headerfile1>
#include<headerfile2>
.
.
#include<headerfilen>
using namespace std;
when I write this(header files are all in standard library of C++),does std namespace of all header files come into picture?
Also, if there are two libraries h1 and h2 and both have same namespace x and in those namespaces have same function func(). How do I resolve this?
From cppreference:
A using-directive that names the inline namespace is implicitly
inserted in the enclosing namespace (similar to the implicit
using-directive for the unnamed namespace).
For instance, in the following example, using namespace std::string_literals makes the operator visible inside the scope:
{ // in C++14, std::literals and its member namespaces are inline
using namespace std::string_literals; // makes visible operator""s
// from std::literals::string_literals
auto str = "abc"s;
}
If you use the using directive outside a scope (for instance as in your example), pain will follow, as the commenters stated, especially if this file is a header file: this namespace will be implicitly imported to any file that includes this one. This is why the proper way of managing a big project is to create your own namespace and put all your custom objects in that new namespace. If you really must use a using directive, do so in the implementation file, never in the header, and ideally within scopes.
This will help you avoid most conflicts, unless your namespace uses a common name:
namespace Matrix{ <--- Bad practice, Matrix will probably conflict with something
myStuff ...
}
namespace JohnsAwesomeMatrix236790{ <--- Namespace name is unique,unlikely to get conflicts.
myStuff ...
}
Also, it is much safer to import the few functions that you use instead of the entire namespace:
using namespace std; // Imports the entire namespace!
using std::cout; // Much better, we only import
using std::endl; // the names of the two functions we use a lot
Any decently written library you include will make very careful use of the using directive (if at all), so you normally don't have to worry about this. However, if you use code written with less stringent standards (e.g., scientific code) this is something to look out for.

STLPORT: What does namespace std{} mean?

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;
}

C++: What's happen when I use "using namespace xyz" before #include<headerxy> [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Ordering of using namespace std; and includes?
I heard that it is strongly prohibited to use "using namespace xy" before "#include ". E.g.
#include <iostream>
using namespace std;
int main() {
...
}
What's the technical reason for that? I tried following and it worked without any problems:
using namespace std;
#include <iostream>
int main() {
....
}
No, it is not strongly prohibited (otherwise it would be a compilation or preprocessing error).
The using keyword puts all functions and variable into the current namespace, and it is discouraged to use it in the header files.
I can think of one good reason. It is that if the namespace hasn't
already been declared, the statement is illegal. At least by my reading
of the standard; most compilers seem to treat the using directive
(using namespace name;) as if it was a declaration
of the namespace, although there's nothing in the standard that I can
find to justify this.
More generally, it's best to avoid namespace directives as much as
possible, except in very limited scopes (and I'd never use a namespace
directive for std, because there's just too much in it which would get
drawn in).
The technical reason is that using will only import anything that is currently visible into the current namespace.
If you're includeing a file after using, you introduce a "weird" order dependency. Of course, this could be what you want, so it is not forbidden by the language. However, you're effectively changing the meaning of headers you're including after the using, since you're exposing the header to a different context (and name lookup might find other names, depending on the context). Name lookup rules can sometimes be subtle, and you don't want to introduce subtleties in someone else's code.
There's an excellent discussion of this in the book "C++ Coding Standards" (Sutter, Alexandrescu), Chapter 59: "Don't write namespace usings in a header file or before an #include"

C++ using for std and boost namespace best practice [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?
I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each and boost::bind. I used in C# and thought that using directives would rock for readability of the code and generally faster development. It would be a pain in the neck to type any namespace before C# foreach statement for example.
What are the cons and pros of using for such popular namespaces I am wondering?
Is it a best practice to include those namespaces or not?
First of all, let's make two distinctions:
1) There are using directives like using namespace std; and using declarations like using std::cout;
2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)
Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.
namespace blah
{
using namespace std; // doesn't pollute the *global* namespace, only blah
}
Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.
Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).
In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.
namespace MyLocalName
{
using namespace boost;
class X
{
// can use things from boost:: here without qualification
};
}
using MyLocalName::X; // brings X back into the global namespace
But never put using namespace boost; or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.
I am against the using namespace statements, except maybe locally in a function's body. It's not a pain at all to write the full-qualified namespace before every identifier, except if you're writing like 500 loc per day.

What's the purpose of: "using namespace"?

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/