About Namespace

May 27, 2011 at 1:48am
Is there any situation where you would want to use option 2 instead of option 1?

option 1) using namespace std;

option 2) using std::cout;
May 27, 2011 at 2:07am
Yes.
1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main() {
   int cin;
   // cin >> cin; //Whoops!
   std::cin >> cin; //Here you still need the prefix, so why bother confusing yourself
   ...
}

I usually use "option 2" in files without a main function and when not in global scope, as to be more careful.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

namespace my_ns {
   using std::ostream;

   class T {
      ...
   };

   ostream& operator<<(ostream &out, const T &t) {
      ...
   }
}
May 27, 2011 at 2:16am
Ideally, no one should ever name a variable or class with the same name as something in the standard library. With that said, you still shouldn't count on other people to not make mistakes.
May 27, 2011 at 8:09am
closed account (z05DSL3A)
using declarations and the using directive have subtle differences
See: http://www.cplusplus.com/forum/beginner/9181/#msg42419
Intrexa wrote:
no one should ever name a variable or class with the same name as something in the standard library.
Isn't that the point of of namespaces, so that you can use the same names in different spaces.
May 27, 2011 at 8:41am
To be honest, I don't really use either. Mostly I just type the std::
May 27, 2011 at 9:02am
closed account (z05DSL3A)
To be honest, I don't really use either. Mostly I just type the std::

Full name qualification is usually best.

Restricting the scope of using declarations and using directives is also better than just dumping them in global scope.
May 27, 2011 at 12:25pm
closed account (zb0S216C)
My rule of thumb: Only use what you need. Put simply, I use Option #2.
May 27, 2011 at 12:33pm
Full name qualification is usually best.

Usually, yes - except when dealing with the std namespace.
Fully qualifying names in the std namespace has little practical advantages, but is a tremendous waste of time.
Topic archived. No new replies allowed.