2

Two ways to use the using declaration are

using std::string;
using std::vector;

or

using namespace std;

which way is better?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Sanfer
  • 414
  • 5
  • 16
  • 2
    They don't do quite the same thing though. – edmz Jul 16 '15 at 09:23
  • 2
    It depends on context, if one was universally better then why would the other one even exist? – Jonathan Wakely Jul 16 '15 at 09:24
  • 1
    @BartekBanachewicz That post does not compare the two types of using declarations but instead is about the good and the bad of std:: prefixes. – Sanfer Jul 16 '15 at 09:24
  • 3
    It has all the information you need to make an informed decision. Have you read it, the question wouldn't be necessary. Besides, those two `using` examples *are not equivalent*. – Bartek Banachewicz Jul 16 '15 at 09:25
  • @JonathanWakely Maybe you could elaborate on a few situations where one is more preferable than the other and vice versa. – Sanfer Jul 16 '15 at 09:27
  • @BartekBanachewicz I had read the question before asking this one. The answer drives an interesting point, but again, the question is more about whether to use using directives and not which using directive is better. – Sanfer Jul 16 '15 at 09:35
  • @Sanfer If you reach a conclusion of "never use `using namespace...`", then it's obvious which one you should prefer. I still believe it's a duplicate. – Bartek Banachewicz Jul 16 '15 at 09:37
  • 2
    @BartekBanachewicz, but that's a foolish conclusion. – Jonathan Wakely Jul 16 '15 at 09:39
  • 1
    It is not easy to write good questions. At the very least, you should have linked the question yours is now marked as a duplicate of, explained what you have taken in consideration from the answers there and made it clearer why your think there is still something to ask. –  Jul 16 '15 at 09:47
  • @BartekBanachewicz there were no conclusions, only supported arguments. "never use using namespaces" has its disadvantages as well, namely, increased code density which I (and many others) wish to avoid. – Sanfer Jul 16 '15 at 09:47
  • 3
    @Sanfer: ...and if this question should be re-opened as not being a duplicate, it will be closed again right away as "opinion based"... which should have been obvious. – DevSolar Jul 16 '15 at 09:49
  • "How do I do zzz?" or "Why is this yyy?" can be answered (more or less) objectively. "Is aaa better than bbb?" is inherently an opinion based question... So the best you can do is consider all available arguments and make up your own mind. –  Jul 16 '15 at 09:52
  • @DevSolar when dealing with questions of style everything is opinion based. Nonetheless there are objective preferences which can be beneficial to the calligraphic coder. – Sanfer Jul 16 '15 at 09:54
  • 4
    I giggled at "objective preferences". – Bartek Banachewicz Jul 16 '15 at 09:56
  • 3
    @Sanfer: Well then, my "objective preference" is to not use `using` *at all* other than for very specific cases like `std::string_literals`. I either write out the namespace (`std::string`), or assign an alias (`namespace sp = boost::spirit::classic`). The reasoning being self-documentation and unambiguousness. And I'd still close the question as opinion-based, becasue *there is no way any of the possible answers could be marked "correct", or even "most helpful"*, and there'd be argueing about it, as you could quite possibly see. – DevSolar Jul 16 '15 at 10:04
  • @DevSolar good to know, although it shouldn't have taken this long to share. Things like self-documenting and unambiguousness are good reasons; they are objective. But stating not to use using is a preference because the compiler doesn't care about style, only syntax, so any style choice is necessarily a preference. Hence objective preference. Anyway, I like your two objective reasons. That's my subjective preference. – Sanfer Jul 16 '15 at 10:17
  • 2
    On terminology: Only `using namespace_name::identifier` is a _using declaration_. The `using namespace_name` thing is called a _using directive_. – sbi Jul 16 '15 at 12:42
  • Yeah... I think the 'duplicated' question doesn't really address what is being (could be) covered here. There are risks with `using`, but that does not mean you can just treat `using` declarations and directives as the same. To be fair, if you throw in 'aliases' (`using t = myLongTypeName`), and maybe take away the 'which is better', this question could stand well as a description of how they differ. – thecoshman Jul 16 '15 at 15:24

2 Answers2

10

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.

Community
  • 1
  • 1
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • 1
    Why was this downvoted? ADL is a great example of when to use `using std::...` – RamblingMad Jul 16 '15 at 09:40
  • 2
    IMHO only the last point makes sense (specialized namespaces like `string_literals` or `placeholders`) but I'd still lean towards making a shorter namespace alias. *where you know exactly what's being included so it's safe* it's dangerous, and has been mentioned in [this answer](http://stackoverflow.com/a/1452738/752976). – Bartek Banachewicz Jul 16 '15 at 09:42
  • 2
    **Moderator note**: comments are not meant for extensive discussions, we have chat rooms for that. I could not be bothered with converting this trainwreck into a chatroom. – Martijn Pieters Jul 16 '15 at 10:38
  • 1
    In short, what advantages do you get from `using namespace` that makes it worth the risk? Yes there are some exceptions (string_literals as you pointed out), but in general, why invite the potential for your code to break because someone else modified a library you use? – thecoshman Jul 16 '15 at 10:43
  • @thecoshman, read the answer again. Notational convenience. Understand the risks, make an informed decision. – Jonathan Wakely Jul 16 '15 at 10:47
  • 3
    @JonathanWakely vOv I guess that's about it then. I get where you are coming from, cargo cult rules are not a good idea. I just see the risks far outweigh the rewards. – thecoshman Jul 16 '15 at 10:53
  • 4
    I sort "notational convenience" waaayyy below "provable correctness" on my list of important traits of the code I have to deal with. Writing the namespace explicitly will objectively make the code clearer to the compiler _and_ to the humans reading it. "Notational convenience" is a very bad excuse for doing any harm to this important goal. I, too, sometimes employ a _using declaration_ or (gasp!) even _using directives_ – but only very rarely and strictly never outside of function scope. No convenience in the world can outweigh the security everything else would do damage to. – sbi Jul 16 '15 at 12:54
  • 5
    I am sure that you know pretty good what you are doing and will probably not make bad decisions. (Even though ISTR Dave Abrahams telling how this once bit him) But look at what questions C++ programmers ask here. Look at what horrendous C++ code is out there, running the critical infrastructure our civilization relies on. Do you really want those C++ programmers to take away the advice "it's OK if you know what you're doing" from your answer? It takes a lot of knowledge to know how little you know, and IMNSHO very few C++ programmers have that knowledge. I'd rather they are safe than sorry. – sbi Jul 16 '15 at 12:56
  • 5
    If this POV makes me disagree with Bjarne, so be it. IME he deals rather gracefully with dissenting opinions. Also, I have said before that I consider it very unfortunate that every C++ book I know skips the `std::` prefixes. Often that's done for layout reasons, but almost as often it's done because the authors have been around long before namespaces were introduced and never got around loving them. I learned C++ in the early 90s and when namespaces came many years later I considered them heaven-sent, because they solved very real problems that I had run into. – sbi Jul 16 '15 at 13:03
1

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.

RamblingMad
  • 5,332
  • 2
  • 24
  • 48
  • Assume that I am only using the standard library. – Sanfer Jul 16 '15 at 09:27
  • 3
    @Sanfer that isn't a realistic assumption – RamblingMad Jul 16 '15 at 09:28
  • The code above only uses the C++14 standard library. However the answer forgets that you need a using-directive or using-declaration to use the `operator""s`! – Jonathan Wakely Jul 16 '15 at 09:28
  • @JonathanWakely forgot about that. Not something worth downvoting for, though. Just needed to be removed. – RamblingMad Jul 16 '15 at 09:30
  • @CoffeeandCode Why isn't it realistic? Besides the question is not if I should use using directives but which one is better to use were I going to use one definitely. – Sanfer Jul 16 '15 at 09:33
  • 3
    @Sanfer Then it should be closed, because that is opinion based. – RamblingMad Jul 16 '15 at 09:34
  • @CoffeeandCode the purpose of inserting a using directive is to reduce code density. That's a general goal which every coder would like. Opinions with objective preferences are the only way to talk about style. – Sanfer Jul 16 '15 at 09:49
  • Even "That's a general goal which every coder would like" is simply your opinion. I don't mind my code being more verbose if it's more readable. – RamblingMad Jul 16 '15 at 09:51
  • 1
    @Sanfer: At least one coder disagrees, and prefers clarity over density any time of the day. – DevSolar Jul 16 '15 at 09:55
  • @CoffeeandCode Replace every by many. The point is that the question could benefit many coders because many of them use using directives, myself included. If the opinions argue around objective preferences, like code density or clarity, then its less opinion based and more objective based. Ultimately it's a matter of preference, and someone might prefer writing code in a monolithic, one-line source file, but that doesn't mean we shouldn't discuss why certain style choices are better than others. As long as the objective reasons behind a preference are stated, we should be good. – Sanfer Jul 16 '15 at 10:03
  • 1
    @Sanfer: The point being that SO is not the place to *discuss*. – DevSolar Jul 16 '15 at 10:06
  • 4
    @Sanfer Then go to [programmers](http://programmers.stackexchange.com/) and discuss it there. Style discussions are not fit for Stack Overflow. – RamblingMad Jul 16 '15 at 10:06
  • 2
    @CoffeeandCode discussions are _very_ poor fit for Programmers - these tend to be quickly voted down and closed over there, see [On discussions and why they don't make good questions](http://meta.programmers.stackexchange.com/q/6742/31260). Recommended reading: **[What goes on Programmers.SE? A guide for Stack Overflow](http://meta.programmers.stackexchange.com/q/7182/31260)** – gnat Jul 16 '15 at 10:23
  • @gnat o_0 I thought Programmers was set up specifically for the more 'discussion' based things we didn't want on SO... where do they go now then? – thecoshman Jul 16 '15 at 10:41
  • @thecoshman did you check [Programmers meta guidance](http://meta.programmers.stackexchange.com/q/7182/312600) referred in prior comment? See also: [Which computer science / programming Stack Exchange do I post in?](http://meta.stackexchange.com/a/129632/165773) – gnat Jul 16 '15 at 10:45
  • well I was mostly just acting up to be honest :D But actually trying to read that now... is there not a non-essay summary of that info? – thecoshman Jul 16 '15 at 10:51
  • @thecoshman in that MSE post: "whiteboard questions, problems that you face while in front of your whiteboard designing your project. Everything that can be considered part of the [SDLC](http://en.wikipedia.org/wiki/Systems_development_life-cycle), except implementation..." – gnat Jul 16 '15 at 10:58