"built-in" functions in C++ - c++

I'm beginner at C++ so if the answer is obvious it possibly is the one I'm looking for. I was reading the second response in this thread and got confused.
#include <algorithm>
#include <cassert>
int
main()
{
using std::swap;
int a(3), b(5);
swap(a, b);
assert(a == 5 && b == 3);
}
What I don't get is "This is just a defined function. What I meant was, why it is not directly built-in" but there was no need to include a new library so isn't it built-in? Does the std library automatically get imported (if yes, why doesn't the namespace automatically get set to std)?

"This is just a defined function. What I meant was, why it is not directly built-in" but there was no need to import a new library so isn't it built-in? Does the std library automatically get imported (if yes, why doesn't the namespace automatically get set to std)?
Well, by defined function it means, most likely that the function is already pre-written, and defined in the library, it isn't directly built-in probably because it was designed that way; only core essentials were included in the language, and everything else is in a library so the programmer can import what they want.
By built-in, usually it's a keyword, like for or while.
And no, std isn't automatically imported since it's designed so the programmer can choose what namespaces they want, like custom namespaces or std. An example of this being bad to automatically have std is this:
Say you automatically defined std, then you wanted to do using namespace foo;, now if foo also had function cout, you would run into a huge problem, like say you wanted to do this;
// code above
cout << "Hello, World" << endl;
// code below
how would the compiler which namespace function to use use? the default or your foo namespace cout? In order to prevent this, there is no default namespace set, leaving it up to the programmer.
Hope that helps!

This is just a defined function. What I meant was, why it is not directly built-in" but there was no need to include a new library so isn't it built-in?
The C++ library is a part of C++, by definition. However, it is not a part of the core language. C++ is a huge, huge language. Making it so the compiler knew every nook and cranny of the language right off the bat would make the compiler huge and slow to load. The philosophy instead is to keep the core somewhat small and give programmers the ability to extend the functionality by #including header files that. specify what they need.
Why doesn't the namespace automatically get set to std?
That would essentially make all kinds of very common words into keywords. The list of words you shouldn't use (keywords, global function in C, words reserved by POSIX or Microsoft, ...) is already huge. Putting the C++ standard library in namespace std is a feature. Putting all of those names in the global namespace would be a huge misfeature.

In your code, you have the line:
using std::swap;
So the call to swap doesn't need std::. For assert, it was defined as a macro, so it also would not need std::. If you did not use using, then other than macros, you would have to use std:: to refer to functions and objects provided by the standard C++ library.
The standard C++ library normally get linked into your program when you compile your program to create an executable. From this point of view, you might consider it "built-in". However, the term "built-in" would usually mean the compiler treats the word swap like a keyword, which is not the case here. swap is a template function defined in the algorithm header file, and assert is a macro defined in cassert.
A namespace is a convenience to allow parts of software to be easily partitioned by name. So if you wanted to define your own swap function, you could put it into your own namespace.
namespace mine {
template <typename T> void swap (T &a, T &b) { /*...*/ }
}
And it would not collide with the standard, or with some library that defined swap without a namespace.

Related

What's the relation between libraries and namespaces?

Just started collage and I'm new in the world of programming. So, as I was learning C++ I bumped into a question that wouldn't let me be : "Why do i need to include "using namespace std" in my code to be able to write or read if i already got iostream?" , because I've been told that "cin/cout" are already defind in iostream library, but I noticed that if I write one of these lines alone it will give a compilation error. And ,therefore, what's the relation between iostream and "std" namespace ...Can someone explain , please? Thank you! <3
#include vs using
In simple terms:
#include <iostream> // include the header
int main() {
// now you can use stuff declared in that header
std::cout << "Hello world" << std::endl;
// if you are lazy you can "use" things:
using std::cout;
using std::endl;
cout << "Hello World" << endl;
}
You do not have to write using namespace std;! The cases where it is appropriate to do that are so rare and the cases where it really does great harm are so frequent that as a rule of thumb you can remember: Never use it! For details see here: Why is “using namespace std;” considered bad practice?. It is imporant to realize that the difference between fully qualifying a name, std::cout, and not fully qualifying the name, cout, is not just about typing 5 characters more or less (read on...).
libraries vs namespaces
What's the relation between libraries and namespaces?
The standard library puts everything in the std namespace. Namespaces help to keep things separated. A different library can contain a other_namespace::vector and there will be no confusion with std::vector because we have namespaces.
the really cool stuff
One deeper reason to use namespaces is Argument Dependent Lookup. I will try to explain with a simple example. Suppose you are using a library with some function template that does something with objects of a type you will have to supply:
namespace library {
template<typename T>
void do_something(T& a,T& b){
std::cout << "wrong...\n";
std::swap(a,b); // (1)
std::cout << "correct\n";
using std::swap;
swap(a,b); // (2)
}
}
I takes two objects and swaps them twice. You have to bear with me for second to understand why (1) is wrong and only (2) is correct. For now we have a library function template and to use that we need some type T:
namespace A {
struct foo{};
void swap(foo& a,foo& b) {
std::cout << "A::swap" << "\n";
}
}
Imagine foo is such that we know a better way than std::swap to swap to instances. Actually foo is empty, so to swap two objects we have to do nothing.
Lets recap: There is std::swap that comes with the standard library. Someone wrote a library (called library) we want to use. We want the library code to call A::swap instead of std::swap. The library author doesn't even know that A::swap exists.
Together with above A and library, this code
int main() {
A::foo a,b;
library::do_something(a,b);
}
will print:
wrong...
correct
A::swap
Live Example. What happened? This line:
std::swap(a,b); // (1)
calls std::swap, no doubt. Not what we want. We would like the library code to call our A::swap.
Now this:
using std::swap;
swap(a,b); // (2)
The first line pulls the name swap from std into the scope of the function. In the second line finally ADL kicks in because it says swap not std::swap. ADL in a nutshell is: a and b are from namespace A, so when the compiler searches for all possible swaps it also searches in A. If it finds one in A then it calls that (and if it does not find one in A there is still the swap coming from std). Hence only (2) calls our custom swap.
This can only work with namespaces. The "cool stuff" is that the library author does not need to know anything about your namespace but still their library code will call your function from your namespace if it exists.
I should note that not all code is generic library code. Often you want to write code where you know what happens in each detail, you want to know what functions get called. Often you do not want your code behave differently depending on a specific header being included or not. Hence, lots of code is better off with fully qualifiying function calls: std::foo.
conclusion
I hope that I could convince you that namespaces is not just about typing some characters more or less. using namespace std; for lazyness completly misses the point of namespaces. On the other hand, pulling names into scope via using std::foo; foo(); is
completely fine and enables ADL.
Libraries and namespaces are related by convention.
By convention, the symbols that a library provides to the programmer-user are contained in a namespace. This organizes things, and there are some higher level language features (ADL) that mean code in a namespace behaves differently than code outside of it.
When you type using namespace std; you tell the compiler "when you run into a symbol, also look into std to find if you can determine what it is". It is generally a really really bad idea to do this at "file" scope; doing it within a single short function is usable, but any more than that can lead to really tricky bugs.
The standard, professional way to interact with namespace std is to prefix your symbols with the namespace:
std::cout << "Hello world\n";
rather than
using namespace std;
cout << "Hello world\n";
and definitely never:
using namespace std;
int main() {
cout << "Hello world\n";
}
you can also grab single symbols, which isn't as bad as importing an entire namespace:
using std::cout;
cout << "Hello world\n";
but should also be avoided at "file" scope.
#include <iostream>
this includes the header file named iostream from the system search path. iostream is part of the standard library. By convention (and the C++ standard), the symbols that iostream provides your program with are located within namespace std.
By putting symbols in a namespace, you avoid conflict with your code. There are many, many symbols in std, and if #include <iostream> shoved some unknown number of symbols into your global namespace, you could easily get errors or the wrong function called in unexpected ways.
std::cout and using namespace std; cout and using std::cout are all ways to tell the compiler in what namespace to find the symbol cout.
#include <iostream> includes cout in namespace std; without it, your code is unaware of its existence.
C++ developed from C, and C has a textual inclusion model. #include actually takes the content of the file iostream and copy/pastes it into your file. Your compiler then reads that extended file and finds the symbols in <iostream>.
Because this textual inclusion could shove a LOT of stuff, having it isolated to a namespace prevents problems for you, the programmer.
Recently, C++ has added modules. Modules are an alternative to #include directives, in that it directly grabs symbols from a library and injects it into your code without a huge copy paste.
In modules, namespaces are still not directly connected to the module. You can
import std;
or
import std.iostream;
and that will just import the std library symbols, still in namespace std, into your code. (the C++ standard added modules, but did not modularize the std library yet, so those names above are speculation).
The symbol lookup is not directly connected to the symbol import.
This lets symbol import be done in large chunks, while lookup be done more carefully.
iostream is a library. It's code someone has written for you so you don't have to do it. By adding #include <iostream> you tell the preprocessor to paste in that code. But the functions and structures that are provided by this code might have names that interfere with others. But that isn't a problem because you can just separate them by putting them in a namespace, the STL(which upstream is part of) does this with std(short for standard, pronounced as 'stood'). When something is in a namespace, you must name that namespace to access stuff in that. i.e. std::cout. But sometimes you don't want to have to write std:: every time you want to access something from the STL. That's what using namespace std does for you. That way, you can just type cout. But this is a very bad idea!
Libraries
Libraries have portions of codes pre-written to provide you with functionalities. Could be in the form of functions/overloaded operators etc.
There are two types of libraries:
Standard Libraries e.g. #include <iostream> and the name of library is in angle brackets.
User defined/made e.g. #include "randomLib.h" and the name of library is in double quotes.
Namespaces
When you require multiple libraries for your project. There is possibility that the both may include multiple methods (function definition) with the same name or a single library may use same function names but in different namespaces. Namespaces are there to remove the confusion or ambiguity for the compiler and user.
Lets say lib 1 has namespace abc{ foo(); } and lib 2 has namespace def{ foo(); }
So you will do abc::foo() or def::foo() for you required functionality. Here abc/def is the namespace, :: is called scope resolution operator and foo() is the method you are calling.

Is it OK to put a standard, pure C header #include directive inside a namespace? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it a good idea to wrap an #include in a namespace block?
I've got a project with a class log in the global namespace (::log).
So, naturally, after #include <cmath>, the compiler gives an error message each time I try to instantiate an object of my log class, because <cmath> pollutes the global namespace with lots of three-letter methods, one of them being the logarithm function log().
So there are three possible solutions, each having their unique ugly side-effects.
Move the log class to it's own namespace and always access it with it's fully qualified name. I really want to avoid this because the logger should be as convenient as possible to use.
Write a mathwrapper.cpp file which is the only file in the project that includes <cmath>, and makes all the required <cmath> functions available through wrappers in a namespace math. I don't want to use this approach because I have to write a wrapper for every single required math function, and it would add additional call penalty (cancelled out partially by the -flto compiler flag)
The solution I'm currently considering:
Replace
#include <cmath>
by
namespace math {
#include "math.h"
}
and then calculating the logarithm function via math::log().
I have tried it out and it does, indeed, compile, link and run as expected. It does, however, have multiple downsides:
It's (obviously) impossible to use <cmath>, because the <cmath> code accesses the functions by their fully qualified names, and it's deprecated to use in C++.
I've got a really, really bad feeling about it, like I'm gonna get attacked and eaten alive by raptors.
So my question is:
Is there any recommendation/convention/etc that forbid putting include directives in namespaces?
Could anything go wrong with
diferent C standard library implementations (I use glibc),
different compilers (I use g++ 4.7, -std=c++11),
linking?
Have you ever tried doing this?
Are there any alternate ways to banish the math functions from the global namespace?
I've found several similar questions on stackoverflow, but most were about including other C++ headers, which obviously is a bad idea, and those that weren't made contradictory statements about linking behaviour for C libraries. Also, would it be beneficial to additionally put the #include <math.h> inside extern "C" {}?
edit
So I decided to do what probably everyone else is doing, and put all of my code in a project namespace, and to access the logger with it's fully qualified name when including <cmath>.
No, the solution that you are considering is not allowed. In practice what it means is that you are changing the meaning of the header file. You are changing all of its declarations to declare differently named functions.
These altered declarations won't match the actual names of the standard library functions so, at link time, none of the standard library functions will resolve calls to the functions declared by the altered declarations unless they happen to have been declared extern "C" which is allowed - but not recommended - for names which come from the C standard library.
ISO/IEC 14882:2011 17.6.2.2/3 [using.headers] applies to the C standard library headers as they are part of the C++ standard library:
A translation unit shall include a header only outside of any external declaration or definition[*], and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.
[*] which would include a namespace definition.
Why not putting a log class in it's own namespace and using typedef namespace::log logger; to avoid name clashes in a more convenient way?
Change your class's name. Not that big of a deal. ;-)
Seriously though, it's not a great idea to put names in the global namespace that collide with names from any standard header. C++03 didn't explicitly permit <cmath> to define ::log. But implementations were chronically non-conforming about that due to the practicalities of defining <cmath> on top of an existing <math.h> (and perhaps also an existing static-link library for some headers, including math). So C++11 ratifies existing practice, and allows <cmath> to dump everything into the global namespace. C++11 also reserves all those names for use with extern "C" linkage, and all function signatures for use with C++ linkage, even if you don't include the header. But more on that later.
Because in C++ any standard header is allowed to define the names from any other standard header (i.e, they're allowed to include each other), this means that any standard header at all can define ::log. So don't use it.
The answer to your question about different implementations is that even if your scheme works to begin with (which isn't guaranteed), in some other implementation there might be a header that you use (or want to use in future in the same TU as your log class), that includes <cmath>, and that you didn't give the namespace math treatment to. Off the top of my head, <random> seems to me a candidate. It provides a whole bunch of continuous random number distributions that plausibly could be implemented inline with math functions.
I suggest Log, but then I like capitalized class names. Partly because they're always distinct from standard types and functions.
Another possibility is to define your class as before and use struct log in place of log. This doesn't clash with the function, for reasons that only become clear if you spend way too much time with the C and C++ standards (you only use log as a class name, not as a function and not as a name with "C" linkage, so you don't infringe on the reserved name. Despite all appearances to the contrary, class names in C++ still inhabit a parallel universe from other names, rather like struct tags do in C).
Unfortunately struct log isn't a simple-type-identifier, so for example you can't create a temporary with struct log(VERY_VERBOSE, TO_FILE). To define a simple-type-identifier:
typedef struct log Log;
Log(VERY_VERBOSE, TO_FILE); // unused temporary object
An example of what I say in a comment below, based on a stated example usage. I think this is valid, but I'm not certain:
#include <iostream>
#include <cmath>
using std::log; // to enforce roughly what the compiler does anyway
enum Foo {
foo, bar
};
std::ostream &log(Foo f) { return std::cout; }
int main() {
log(foo) << log(10) << "\n";
}
It is ugly hack too, but I believe will not cause any linker problems. Just redefine log name from <math.h>
#define log math_log
#include <math.h>
#undef log
It could cause problems with inline functions from math using this log, but maybe you'd be lucky...
Math log() is still accessible but it's not easy. Within functions where you want to use it, just repeat its real declaration:
int somefunc() {
double log(double); // not sure if correct
return log(1.1);
}

Wrapping external libraries in namespaces

I'm writing a library to use in my projects. In it, I was hoping to wrap the c standard library in my library's namespace and a cstd namespace to avoid having its functions in the global namespace. However, from a previous question I asked and from what I've tested, I can't just #include everything in a namespace. Is there any way to do this?
I doubt it, unless you wanted to rewrite everything.
The C language itself has no concept of namespaces, so everything the C standard library uses must rely on the fact that whatever it is looking for resides in the global namespace.
If you simply wrapped a namespace around your #includes, the compiler wouldn't be able to find anything because it wouldn't know what namespace to look in.
The usual approach would be to put the 3rd party includes in the implementation files to keep them from polluting your api.
myapi.hpp
void coolthing( int howcool );
myapi.cpp
#include <coollib.h>
void coolthing( int howcool )
{
coollib_coolthing( howcool );
}

C++ namespace and include

Why do we need both using namespace and include directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?
(I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)
using directives and include preprocessor directives are two different things. The include roughly corresponds to the CLASSPATH environment variable of Java, or the -cp option of the java virtual machine.
What it does is making the types known to the compiler. Just including <string> for example will make you able to refer to std::string :
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
Now, using directives are like import in Java. They make names visible in the scope they appear in, so you don't have to fully qualify them anymore. Like in Java, names used must be known before they can be made visible:
#include <string> // CLASSPATH, or -cp
#include <iostream>
// without import in java you would have to type java.lang.String .
// note it happens that java has a special rule to import java.lang.*
// automatically. but that doesn't happen for other packages
// (java.net for example). But for simplicity, i'm just using java.lang here.
using std::string; // import java.lang.String;
using namespace std; // import java.lang.*;
int main() {
cout << string("hello, i'm a string");
}
It's bad practice to use a using directive in header files, because that means every other source file that happens to include it will see those names using unqualified name lookup. Unlike in Java, where you only make names visible to the package the import line appears in, In C++ it can affect the whole program, if they include that file directly or indirectly.
Be careful when doing it at global scope even in implementation files. Better to use them as local as possible. For namespace std, i never use that. I, and many other people, just always write std:: in front of names. But if you happen to do it, do it like this:
#include <string>
#include <iostream>
int main() {
using namespace std;
cout << string("hello, i'm a string");
}
For what namespaces are and why you need them, please read the proposal Bjarne Stroustrup gave 1993 for adding them to the upcoming C++ Standard. It's well written:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf
In C++ the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.
Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
In C++ #include and using have different functions.
#include puts the text of the included file into your source file (actually translation unit), namespaces on the other hand are just a mechanism for having unique names so that different people can create a "foo" object.
This comes from C++ not having the concept of a module.
Keep in mind that namespaces in C++ are open, that means that different files can define different parts of the same namespace (sort of like .NET's partial classes).
//a.h
namespace eg {
void foo();
}
//b.h
namespace eg {
void bar();
}
The include is defining the existence of the functions.
The using is making it easier to use them.
cout as defined in iostream is actually named "std::cout".
You could avoid using the namespace by writing.
std::cout << "Hello World";
These keywords are used for different purposes.
The using keyword makes a name from a namespace available for use in the current declarative region. Its mostly for convenience so that you do not have to use the fully qualified name all the time. This page explains it in some detail.
The #include statement is a pre processor directive and it tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. That is, you can think of this statement as copying the included file into the current one. The compiler then compiles the entire file as if you wrote all the code in one big file.
As pointed out, C++ and Java are different languages, and do somewhat different things. Further, C++ is more of a 'jest grew' language, and Java more of a designed language.
While using namespace std; isn't necessarily a bad idea, using it for all namespaces will eliminate the whole benefit. Namespaces exist so that you can write modules without regard to name clashes with other modules, and using namespace this; using namespace that; can create ambiguities.
I think the other answers are missing the point slightly. In all of C++, Java and C#, the using/import thing is entirely optional. So that's not different.
And then you have to do something else to make code be visible anyway, in all three platforms.
In C++, you minimally have to include it into the current translation unit (good enough for many implementations of vector, string, etc.), often you have to add something to your linker as well, although some libraries do that automatically based on the include (e.g. boost when building on Windows).
And in C# you have to add a reference to the other assembly. That takes care of the equivalent of includes and link settings.
And in Java you have to ensure the code is on the classpath, e.g. adding the relevant jar to it.
So there are very closely analogous things required on all three platforms, and the separation between using/import (a convenience) and actual linkage resolution (a requirement) is the same in all three.
You need to understand namespaces if you want to truly understand this.
With include you are just including the header file.
With using namespace you are declaring you are using a given namespace that contains stuff such as cout. so if you do this:
using namespace std;
to you use cout you can just do
cout << "Namespaces are good Fun";
instead of:
std::cout << "Namespaces are Awesome";
Note that if you do not #include <iostream> you won't be able to use neither std::cout nor cout in your declarations and so forth because you're not including the header.
One liner (not that this is something new :)):
using std allows you to omit std:: prefix, but you cannot use cout at all without iostream.
Even Stroustrup refers to the #include mechanism as somewhat hackish. However it does make separate compilation much easier (ship compiled libraries and headers instead of all source code).
The question really is "why did C++ -- after it already had the #include mechanism -- add namespaces?"
The best example I know of about why #include isn't enough comes from Sun. Apparently Sun developers had some trouble with one of their products because they had written a mktemp() function that happened to have the same signature as a mktemp() function that was included through from a file that was itself included through a header the project actually wanted.
Of course the two functions were not compatible, and one could not be used as a substitute for the other. On the other hand, the compiler and linker did not realize this when building the binary, and sometimes mktemp() would call one function, and sometimes it would call another, based on the order different files were compiled or linked.
The problem stems from the fact that C++ was originally compatible with -- and essentially piggy-backed on top of -- C. And C has only a global namespace. C++ solved this problem -- in code that is not compatible with C -- through namespaces.
Both C# and Java (1) have a namespace mechanism (namespace in C#, package in Java), (2) are usually developed through IDEs that handle referring to binaries for the developer, and (3) don't allow freestanding functions (a class scope is something of a namespace, and reduces the risk of polluting the global namespace) so they have a different solution to this problem. However, it is still possible to have some ambiguity regarding which method you're calling (say, a name clash between two interfaces that a class inherits), and in that case all three languages require the programmer to clearly specify which method they're actually looking for, usually by prepending the parent class/interface name.
In C++, the include directive will copy and paste the header file into your source code in the preprocessing step. It should be noted that a header file generally contains functions and classes declared within a namespace. For example, the <vector> header might look similar to something like this:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
Supposing you need to define a vector in your main function, you do #include <vector> and you have the piece of code above in your code now:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
int main(){
/*you want to use vector here*/
}
Notice that in your code the vector class is still located in the std namespace. However, your main function is in the default global namespace, so simply including the header will not make the vector class visible in global namespace. You have to either use using or do prefixing like std::vector.

Do you prefer explicit namespaces or 'using' in C++?

When using C++ namespaces, do you prefer to explicitly name them, like this:
std::cout << "Hello, world!\n";
Or do you prefer using namespace:
using namespace std;
cout << "Hello, world!\n";
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.
I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own "strings", "vectors" etc to maintain. The more information the code carries with it, the better.
Extra typing is not the issue here. The problem with explicitly qualified names is the visual clutter. Let's face it, C++ syntax is untidy. No need to make this worse by needlessly making names longer and sprinkling the code generously with ::s.
I'm with Jeff Atwood: The Best Code is No Code At All. This is so true.
Namespace imports are a great way of reducing clutter with no drawback: As long as the scope of opened namespaces is reduced to a single compilation unit1, name conflicts, should they appear, can be resolved easily.
Why explicit names should (in general) be more readable has always been a mystery to me. The readers should generally know the code good enough to be able to deduce semantics. If they aren't, the code needs fixing anyway.
1) Corollary: no using in headers!
I always use using namespace for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use using namespace to avoid polluting the global namespace of the #including source.
My general rule is always explicitly use the namespace in headers, and usually use using in the code. The reason for the former is to make it explicitly clear in every part of the definition what is being used, and the reason for the latter is that it makes it easy to use replacements from another namespace if that becomes necessary. i.e. if we want to start using foo::string instead of std::string we just need to update the header and the using statement rather than replacing every instance of std::string with foo::string in the code.
Of course, that is less useful for classes that reside in the std:: namespace, since even if you replace one class you're still likely to use others in std, and may run into ambiguity issues, but that was just an example.
using and using namespace are Very Very useful to render the code more readable - remove clutter.
But in any case where it makes it harder to find out where a symbol comes from, I refuse importing it's whole namespace.
I try to limiit the scope of the imported namespaces:
void bar() {
// do stuff without vector
{ using std::vector;
// do stuff with vector
}
// do stuff without vector
}
For "generally known" libraries, like std, I would dare using using namespace std. There is reason to believe everyone reading this code knows these symbols.
As a sidenote, the using keyword is also used to indicate that a derived class also exports the overloaded members of its superclass.
class A {
void f( A );
void f( bool );
};
class B : public A {
using A::f; // without this, we get a compilation error in foo()
void f(bool);
};
void foo() {
B b;
b.f( A() ); // here's a compilation error when no `using` is used in B
}
I only use explicit namespaces when there's some ambiguity. It is more readable, but the extra typing is too tedious, and you have to assume other developers have a baseline level of familiarity with standard libraries.
The only other times I spell out a namespace are when I'm only using it once or twice, like adding in a quick debug statement, or if I'm using some non-standard library.
I typically declare the namespace at file scope, but if you're mixing namespaces it might make sense to put the declaration closer to the point where it's used, in function scope.
using at function scope, or if the function is very small (often is), just explicit namespace
I tend to explicitly import the names that I need at the top of the .cpp file, so...
using std::cout;
using std::endl;
etc...
That way I have control over the names that I use and it's easy to see where they come from and the code isn't cluttered at the point of use.
In the rare cases where I am using two names from different namespaces I fully qualify them at the point of use.
I always use fully qualified names in headers and hardly ever use 'using namespace x' anywhere...