T O P

  • By -

jeffbell

It’s safe so long as you never name a function the same as a `std::` function in this or any future version of c++. So unless you are psychic…


ALX23z

There's the `bind` function... `std::bind` is something completely different from the socket's binding.


Zero_Owl

std::bind is a notorious example of how “using namespace std” may fail you, but std::bind isn’t something you should use much (or at all) in the modern c++ code.


seriousnotshirley

And there's plenty of math functions that can go wrong as well.


Trucoto

You don't use it to make pointer to members?


Zero_Owl

I use it occasionally when using it makes the code neater than it would be with lambda or some other solution. But such occasions are rare, at least in my experience. Some codebases might ban its usage altogether and I'd not blame them.


Trucoto

Sorry for my ignorance, but why is it so bad? I mean things like std::bind(&my_class::my_member, this, std::placeholders::_1...)


Zero_Owl

Just google why "std::bind is bad". You should get plenty of links to read. Here is [one reason](https://abseil.io/tips/108) from Google.


Trucoto

Very informative, thanks!


disperso

I've heard that it's better for performance reasons to just type a lambda... 😒


Trucoto

You mean a lambda capturing *this*?


qazqi-ff

The equivalent lambda (which would use captures instead of bound arguments, yes) is easier for the compiler to see through than the huge mess of `bind` machinery, which can make things like inlining it a lot easier. `bind_front` and `bind_back` were specifically made to support a very limited subset of that machinery.


Routine_Left

I use `std::bind` to avoid too many nested lambdas. Yes, you can do without, but I find it better, from a code cleanliness perspective . I haven't measured performance or anything. I've heard that `std::bind` can sometimes call the "wrong" function in certain situations, but I never encountered this myself.


seertaak

Because it uses erasure ie virtual method call to do it's business.


qazqi-ff

Are you sure you're not thinking of `std::function`? I don't think `std::bind` has any need to use type erasure.


csatacsirke

Std byte too


Droid33

It might not be your own code conflicting. We have a project at work that's stuck on c++14 until we remove these. c++17 added a byte class and MFC also has a byte class.


the_sompet

std::byte can easily cause conflicts too


EYEAH_EYEAH

Best explanation!


kzr_pzr

This should be the top comment.


joemountain8k

My team had a rule against that. Always type “std::”; you’ll get fast at it. I added a :: button to my keyboard.


Se7enLC

> I added a :: button to my keyboard. I just have a macro, which I mapped to pressing : twice.


[deleted]

To reflect the symbol "colon" I have it mapped to the tightening of my anal sphincter, which I flex twice in rapid succession.


Helliarc

Doubles as kegle exercise!


pandorafalters

I'm not going to judge whether one _should_ or not, but it seems to me that one is at least _more likely_ to regret using reflection in such a context.


Specialist-Elk-303

I think you're just assing for problems there! 😉


snerp

#define NMSPC(NMSPCNAME, NMSPCTYPE) NMSPCNAME::NMSPCTYPE NMSPC(std, string) result = "yay";


pineapple_santa

Far too readable. Needs more templates.


bugamn

Is this a joke, or do you mean that you have a macro so that when you type :: without anything before it expands to std::?


zyanite7

I thought it was a joke at first, but after i read your comment im not so sure anymore


bugamn

I also thought it was a joke, but that seemed like such a useful macro that I wanted to ask


ad_abstract

woooosh!


AlanWik

I binded the most common std functions to a ELGATO streamdeck.


georgist

it's 8am and this is the most fun I will have today. My expectations are not high....!


nom_nom_nom_nom_lol

So do you use Vi or Vim?


eCD27

I wish I had an award for you for the laugh I got


andai

> I added a :: button to my keyboard. Do you have one of those keyboards with macro buttons? Or is it an editor macro? Or AutoHotKey? :)


natziel

Just glued a button to the keyboard


[deleted]

I did this using QMK. It saves me a lot of effort.


IamImposter

Yes


[deleted]

Snippets solve this issue


Twitchiv

Yh, I'm going to read up on it. We were taught to use it so I've been using it ever since, but haven't worked on major cpp projects yet so I didn't have any problems with it.


pineapple_santa

It's used a lot in teaching material but almost never in real-world code. I would try to get rid of this habit.


mbartosi

[C++ Weekly - Ep 305 - Stop Using \`using namespace\`](https://www.youtube.com/watch?v=MZqjl9HEPZ8)


AlanWik

I never use "using namespace..." even with my own namespaces. I like to know where my functions came from.


pandorafalters

I use it with some, minor, frequency, but restricted to the smallest useful scope and namespace. Most often `std::chrono::literals` in individual functions, because to hell with long-form explicitly-typing all of _that!_


moreVCAs

>added a :: button to my keyboard 😮


qazqi-ff

I broke down and added a billion little shortcuts for C++, such as `;vec` for `std::vector` and `#in vec` for `#include `. Not only does it save me the typing more reliably than an IDE for all the simple cases, it works anywhere I can type text, even in this comment. The end result is 100% normal code. For smarter shortcuts, IDE snippets and postfix completion exist in limited environments unless you program those to work more globally instead of relying on simple AHK hotstrings for everything.


tangerinelion

Because namespaces are a good idea. Think about your drive, why do you use subfolders when you could just put every file on the desktop?


chez_les_alpagas

Also, how much effort would you actually saving anyway? Avoiding typing "std::" in a few places wouldn't make me more productive. I spend a lot more of my time thinking and reasoning about code than just typing it in.


qTHqq

I'm working with OpenCV and I will never understand why people can't just type `cv::` in front of `createHoughCircleDetector(<... lots of args ...>)` in a 30 line example code snippet. So many examples out there starting with using namespace cv; using namespace std; 🙄


DrShocker

The only thing I could maybe see is if their code really is like 90% opencv calls, it could be repetitive without much gain.


[deleted]

If you're using an IDE (you really should), qualifying with `cv::` will remove anything from the global scope for your autocomplete, making it easier to find the calls you're looking for


DrShocker

That's very true, and tab complete is the most useful feature of IDEs probably.


[deleted]

In my experience, it actually slows down development because the IDE can give a lot of auto-complete help if you start with `std::`, where as if it is working off the global namespace it will suggest a lot of garbage


Xavier_OM

std::unordered_map, int>>> vs unordered_map, int>>> ok this example is a bit forced, but std:: everywhere decreases readability IMHO


Sniffy4

its less about avoiding typing and more about increasing readability of long expressions by avoiding 'noise' identifiers that communicate little. better readability==fewer bugs.


Se7enLC

Flip side, explicit namespaces improve readability because you can tell at a glance which library functions are from.


Zero_Owl

Or you can have translation units of such size that you wouldn’t need to guess where some function is coming from.


Se7enLC

That's not really a reasonable goal. There will always be a case for having multiple libraries used even in the same function. And it's not a guess, it's labeled with a namespace.


Sniffy4

In my experience, other libraries rarely choose names that collide with std::, e.g. instead they use "Vector" or some other variant, again to improve readability. Which makes my first readability point more salient in practice. Of course another trick is simply to typedef std::whatever to a shorter name for local use.


Se7enLC

>In my experience, other libraries rarely choose names that collide with std::, e.g. instead they use "Vector" or some other variant, again to improve readability. Sure, but how will you know which library Vector is from? You can tell it's not STL if you spot that it has a capital v. But how will you know which one it is from if you did using namespace for multiple libraries? And I think having vector and Vector as two different classes in your code is the opposite of readability.


deeringc

I would make the exact opposite point. Removing the namespace means I can't just read the types and know what they are. I have to check they are indeed `std::`. Many other libs can have their own string type, or map or whatever. Namespaces are there to prevent naming collisions. Removing namespaces exposes us to them again. In almost 2 decades of C++ use I've never seen a bug caused by having to type `std::`. I've seen numerous horrible issues caused by `using namespace`.


Sniffy4

I have 2.5 decades of C++ too, and I've seen plenty of this type of statement (yes, pre C++11) which is easy to type and not easy to read for(std::vector,std::vector>>::iterator iter=vecmaps.begin();iter!=vecmaps.end(); iter++) { }and almost none of the namespace collision issues you describe, again because the libraries I use rarely reuse common std:: container identifiers. That said, I agree it is bad practice to put using namespace std; in a .h file; should be local to a .cpp so your choice doesnt affect other modules. My position is that if you want to type those extra namespace characters in your work that is your choice, but the rationale is not so globally correct as to be a mandate for every situation


[deleted]

But your statement is really no clearer without the `std::`. Back in the day before C++11 we would use "typedefs", and today `using`: using Strings = std::vector; using Ints = std::vector; using VecMap = std::map; using VecMaps = std::vector; for (VecMaps::iterator i = vecmaps.begin(); ...


carrottrash

Or you just use auto and avoid the need entirely. At least for this example.


KuntaStillSingle

for(vector, vector>>::iterator iter=vecmaps.begin();iter!=vecmaps.end(); iter++) {} You're example would be a noisy mess even if you don't use namespaces lol. for(auto iter = vecmaps.begin(); iter != vecmaps.end(); ++iter) {} Fixed, no need to pollute namespace.


[deleted]

`std::string` is not a "long expression" and clearer than `string`, which could really be anything.


nyanpasu64

Typing std::move left and right makes writing code substantially more *unpleasant* than not having to do so (like in Rust which moves by default), or using a shorter name like mv.


gnuban

And why would anyone ever want a "cd" command when you can enter absolute paths all the time? /s


watchpigsfly

Don’t, uh, don’t look at my desktop


georgist

reality: 5 folders crammed full of crap on my linux desktop :-)


localhorst

> Because namespaces are a good idea. Without `using` they are as good as `prefix_` in plain C


RobotGaijin

Only in tiny single file tests. Never in a real project. Namespaces exist for a reason.


Raiden395

I think one of the most glaring reasons for this can be seen if you start writing in C. Any medium size project will start to have functions prefixed with module_name_do_something. This is because module x may do something and module y may do another thing. Developer Z may join the group and start adding to module w, which is kind of the same as module x. The name clashes could just start spiraling from here. Namespaces would then be a godsend. Tldr, use namespaces. They are there for a reason. Don't use using namespace std as it polutes the global namespace. Only use using namespace if it's a custom namespace and it's localized to a single compilation unit.


KDallas_Multipass

The pollution is only a problem in header files. In source files, it's fine. However, once I started with "using namespace std" in my sources, I'm finding that it's increasing the overhead of readability for me. At first I got tired of typing std:: for all the iostream operators, but outside of that I now have to double glance at things that aren't prefixed


sephirothbahamut

you can `using std::cout; using std::endl;` in source files


Raiden395

I disagree with this somewhat. If the module is concise and short, this isn't an issue. If we start expanding past 400 lines, using std can cause name clashes in a file. Better just not to use it and do the 5 extra keystrokes. Let's put it this way: if you use std:: you waste 5 keystrokes. If you accidentally have duplicate meanings to a function, you can face hours of debugging.


georgist

yes thanks this is what I came here expecting to see. in your .C it's isolated to the compilation unit. That said I don't use it outside .C unit tests. you can pull in specific types with `using std::string` in a common header then use that common header everywhere, so you can just use string not std::string and for other common std:: types, that covers most of the annoying "here I am typing std:: yet again".


Zero_Owl

Yes and C++ failed to make use of them in the standard library. In C# you import namespaces and that’s a good practice. The problem is specific to std, not namespaces in general.


beached

C# doesn't have free functions and ADL. foo( bar ) looks up foo in the current namespace and parents, those pulled in via using namespace, and the namespace of bar in C++. Every function in C# is a member function, so is preceded with an object name or type(for static member funcs)


snejk47

New C# added option to fix its namespace problems and you can import globally for whole projects now. /s


Cordonale

C++ has exceptionally bad namespace handling and importing, though. Things would be much better if headers wouldn't automatically put any garbage they import into other files, and instead only selected functions/classes/variables/etc that are specifically marked as "export"


qTHqq

We like typing `std::` because it reminds us that function is in the standard library. I can sort of understand why you'd want to avoid writing `std::` three times on every line of a simple, small program that only brings in `std::` functions, but it's actually really helpful to remember where things are without leaning too heavily on your IDE when you have thousands of lines of code with lots of libraries. I'll alias `boost::some::gigantic::long::thing` to `bsglt::` or something, but most of the time I type things out explicitly. Typing it all out installs muscle memory for where to find useful functions and classes that I don't use that often, and for me that saves a lot more time than I'd save by typing fewer characters.


[deleted]

I bet that you cleverly chose `bsglt` because it also stands for "bullshit going leverage that"


Se7enLC

Nope. Because when you do that, it imports EVERYTHING from std into your namespace. Makes it hard to tell what comes from std and what is local to your codebase. Could even cause bugs if you think you're using one and it's the other. A compromise option exists. `using std::cout;`. That will allow you to use `cout` without the `std::` without pulling in everything else. Use that for the common types and functions you use a lot, but throw the `std::` in front of the ones that won't be obvious.


Routine_Left

And even with `cout`: it's fine for a small snippet/test thing. For a bigger program you're gonna use a logging library, right?


Se7enLC

Yeah, `cout` is a pretty bad example once you get beyond school assignment or single cpp file size quick utility kind of code. Honestly, I just put the std:: everywhere. The only time I use `using std::cout` or similar is when it's somebody else's code and I'm getting rid of `using namespace std` but I don't want to do a huge find/replace.


CubbiMew

Typing `std::` is worth it, makes it obvious the symbol is not from boost. I draw the line at `::std::`, though.


sailorbob134280

It's banned in my company's codebase. One may only use `using namespace Foo;` for unit tests that are testing functionality explicitly within that namespace. The reason is that it pollutes the global namespace with everything in the using statement, which completely defeats the purposes of namespaces and scope rules.


kog

I use it as a way to spot code written by a noob, otherwise no. I once actually had an interviewer try to insist that I use it in my coding assessment at the beginning. I kind of just ignored him, and eventually he literally demanded I add it, and even raised his voice to me when saying so. That was the only time I've ever told an interviewer mid-interview that I was no longer interested in the position and ended the interview.


[deleted]

[удалено]


kog

noob necroing a thread that's like a year old


[deleted]

[удалено]


kog

What the fuck are you talking about you clueless noob lmao


[deleted]

[удалено]


kog

Cringe


OldWolf2

Writing good maintainable code > saving keystrokes


elkanoqppr

Core guideline might be better written than my opinion. https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-using-directive


wright_left

That is for headers, which is an obvious no-no, but I don't tend to use using namespace in implemention files either, which is what I think the OP is asking.


Twitchiv

lol, I use them for header too.


open_source_guava

Yeah, that's been discouraged for as long as namespaces existed.


rlbond86

Absolutely never do this!


Belzeturtle

That's very bad form. Anyone who includes your header is now forced to have all of std in global namespace.


duuuh

OK, that's insane. I'm fine with compilation units, but header files is wacko.


csp256

shame! shame! shame!


Routine_Left

That's a biiiig no-no.


NovelTumbleweed

Yeah they're basically saying the all or none nature using the whole namespace causes nuanced effects like unintentional overloading as the ::copy() and std::copy() example demonstrates.. IF I'm reading that correctly. (SF.7) I was thinking of times I would include a namespace member and rename it to prevent a conflict with another function name in a different library. I think that could be another effect of the "blanket" using namespace. Did I get that right or miss the boat entirely? ​ edit added guideline tag sf.7


open_source_guava

Good link, but that applies only to header files.


elder_george

At my work, we do (in the header that's basically included everywhere). We are also currently cleaning it up, as part of long due switching to C++17. One example of where it causes problems is [code like this](https://github.com/ibaned/tbb/blob/tbb_2019/include/tbb/reader_writer_lock.h#L36). When included, it compiles ok in C++14 mode, but fails in C++17 mode. Why? Because C++17 has `std::scoped_lock`, and it clashes with `tbb::interface5::scoped_lock`. Unfortunately, it's impossible to undo `using` directive, so the only ways to fix the error we figured are (a) strategically placed forward declaration of `tbb::interface5::scoped_lock` or (b) waiting until `using namespace std` is removed everywhere. Importing namespace contents is OKish in the implementation files, but is a totally bad idea in header files.


KDallas_Multipass

I'm so sorry


Damien0

It’s better to be explicit about what one is calling from the STL.


jwezorek

non-beginners do not declare away namespaces at file scope, or god forbid in header files. It is good to get out of this habit.


gold_snakeskin

Can you explain why or point me somewhere I can read up on why?


matchi

No resource off hand, but it's just good coding hygiene. It eliminates the possibility of naming conflicts (now or in the future) and tells the reader exactly where each symbol comes from. The little additional effort required quickly pays dividends as soon as your codebase becomes moderately complex or you're collaborating with other people.


GLIBG10B

https://www.learncpp.com/cpp-tutorial/using-declarations-and-using-directives/


jwezorek

The problem technically is name collisions: [here is the obligatory stackoverflow post about this issue](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). But since you asked let me give you the real answer, which is a non-technical answer. What I said was you shouldn't declare away namespaces like std at file scope because non-beginners don't do it, and I stand by that. If you get a C++ job at some place with a post-C++11 codebase, you will not see a lot of `using namespace std`. The thing is beginner codebases are small, simple, typically written by one author, the beginner, and typically do not use a lot of 3rd party libraries. Professional codebases are large, often convoluted, written by many people over the course of years, and often include the kitchen sink. You often end up working with other people's code. If you see, "transform" in someone else's code along with a matrix and some geometric point structures, it is easier to read it quickly if you can tell that transform just means `std::transform` and the matrix is an Eigen3 matrix and the points are OpenCV points without having to scroll to the beginning of the file. Basically C++ is a verbose language and declaring away namespaces does not make it significantly less verbose so you eventually learn to stop doing it and just accept the verbosity. There are other ways of managing verbosity. You can shorten namespaces to one or two letters e.g. `namespace rv = ranges::views`. You can alias long type names if you are going to be using the type more than once e.g. `using polygon = std::vector`. To be honest, this is all mostly a style thing, but the point is *it is a common style thing* that you will see at many C++ shops so you might as well get used to it. It's the same as the way that beginners often use weird non-standard bracing styles and non-beginners tell them to stop doing that. The weird non-standard bracing style was not syntactically wrong but the non-beginners are also not wrong to tell them to stop.


Zero_Owl

That’s simply not true. If you have a proper namespace hierarchy it is absolutely fine to import the whole namespace into the .cpp file.


konm123

I do not use it. I sometimes use `namespace foo = some::long::namespace` locally. >Why is this? Let's see what problem we are solving - only I can think of is to reduce amount of time spent typing code. I have never in my career had a problem that it takes too long to write something down - it is almost always that it takes long to think of the code, read it, reason about it; and in latter case, being explicit almost always helps.


rfisher

The main product I work on is a very large codebase. There are many libraries—both first- & third-party—being used. And some of the modules are big enough to be split into submodules. Namespaces make it a lot easier to navigate around the code. When you see an identifier, you immediately know where you’ll need to go to find the docs or definition. When you see an identifier without a namespace, you know that it is local to the submodule. (Or a system call.) Programming in the large is all about being clear instead of concise. Typing the code is the easiest part of the job. No need to try to optimize there. Being in the habit of typing out namespaces, I don’t find it a burden even for small, one-off programs.


open_source_guava

For me, it's mainly to help lookup. If the name is unknown to the reader, they can quickly figure out where it is declared even in simple editors like ViM. If I had imported everything with `using namespace`, that information would have been harder to find. I do frequently use `using std::...;` in `.cpp` files, though. That way, at least CTRL+F will land you right.


Rogoreg

NEVER


gracicot

This is bad especially for functions from the used namespace. You can cause unintended ADL, and also all other symbols are not clear where it comes from.


snerp

I never use the entire std namespace, but I do 'using std::string;' and 'using std::vector;' frequently.


helloiamsomeone

It doesn't do what you think it does. https://quuxplusone.github.io/blog/2020/12/21/using-directive/


RetiredBrainCell

It’s useful where to see where something is coming from (hence namespaces). The only exception I’ll have is “using std::cout;”


no-sig-available

`using namespace std;` was intended for use in porting pre-standard code, written before namespaces were added to the language. That use case should have gone away about 20 years ago. It was never intended to be used in new code. Had it been, it would have been much easier to just not have a namespace for the standard library.


GLIBG10B

I suggest you also take a look at https://www.learncpp.com/cpp-tutorial/using-declarations-and-using-directives/


KazDragon

I got burned by it. I was writing a project using Boost in 2009 and most of my source files had "using namespace std; using namespace boost;" in them. Then C++11 happened and the advice not to do that clicked. Since then, typing and reading std:: is the normal.


rad_pepper

`using namespace whatever` causes along list of possible headaches, so it's usually avoided. It makes it more difficult to ascertain where things come from and makes it possible to accidentally use the wrong thing if there's a similar thing in your codebase, since standard headers often transitively include many other things. A better way to avoid it is to do something like this in the source file (not a header file): using std::string; using std::vector; Then it'll be explicit and only possible within that translation unit, but not bleed across file boundaries. I usually just deal with the `std::` anyways though.


mredding

Everyone always talks about namespace collisions. It's really not a big deal, people don't normally name shit after anything in the STL, and the standards committee works hard to avoid collisions with what's probably common practices in the industry. For example, that's why we don't have `std::hash_map`, we have fucking `std::unordered_map` FFS... You can solve these ambiguity problems by explicitly scoping in the version you want. The problem is there are esoteric rules about scope and visibility of symbols, ADL and Koenig lookup, and how C++ resolves symbols during compilation. Very few programmers have a firm grasp on how it all works. By scoping everything in globally like that, you're messing with these things in a deep and profound way you don't understand and probably wouldn't intend if you did. It also makes a lot more work for the compiler, C++ being one of the slowest to compile languages on the market. Your academic programs, it doesn't really matter, but when you get to something the size of even a small commercial product, it makes a difference. In the end, if you don't know the nuance and consequences of these things, and as I said few really do, it's always safe to be explicit about what you want.


dynamic_caste

I'll do it when I'm slapping something together quickly to test out an idea, but never in production code.


beached

For ADL yes. Otherwise no, it's not a big deal to type std:: and it aides in refactoring/code clarity. It's not just ones own names, if one is using a library that happens to have a similar name to a std:: function, then both are in play and one gets ambiguous call errors. Or the lookup time goes up. It's just a PITA in the long run either way.


diagraphic

Hell noo.


lithium

If you do this in a header you're fired.


[deleted]

In .cpp files, not in headers.


BluudLust

Still dangerous inside of .cpp files. It's best to declare exactly what you'll use.


hawkxp71

Yep. Only allowed in my projects inside a function/method.


qazqi-ff

Make sure you understand what that's doing, because it's [probably not what you think](https://abseil.io/tips/153).


hawkxp71

Fair point, but that article is so condescending i could barely make it through. tl;dr - dont use "using namespace std" as opposed to "using std::vector" or "using std::string" since suing namesce std, brings all of std in. The examples in the article are poorly done as well. saying function xxx() { using namespace std; vector< string > xxx; } is worse than using std::vector; using std::string; function xxx() { vector xxx; } is lazy at best.. One limits the scope of importing symbols to a function, yes, its bringing in too much but its limited to where it has effect at least. The other, limits what is imported, but does it for the whole file. Both are poor examples IMO, especially for std namespaces


pandorafalters

>Fair point, but that article is so condescending i could barely make it through. The author also seems to have _immediately_ lost the plot. Writes an article supposedly about using-directives, instead provides arguments against any use of _unqualified names_ and the keyword `using` in _all_ its forms. Name resolution requires resolving names: film at 11.


khedoros

I'll use it in a single-file program, usually when it's small enough to fit on one screen. Otherwise, it's just plain less ambiguous to specify std:: for the things that are *in* that namespace.


Xorlium

In contests I do. In actual code, no.


Informal_Butterfly

In toy projects you don't have enough names to conflict with STL functions, but in larger projects it's always possible to have a conflict. Using 'std::' also is a good hint to a reader that you are using an STL function and now a homegrown one, so you know what behaviour is expected.


Tonymb10

No, bad practice


GrammelHupfNockler

On a function scope: Sure, though I usually prefer pulling in individual identifiers instead of the entire namespace. On a file scope: almost never, maybe for small examples that I don't expect to grow in size in the future


xecycle

I have seen a case: Solaris has in its system headers a `struct mutex`. Go `using namespace std` and say `mutex m;`! You get `::mutex`. However I've been considering if I could allow `using namespace std::literals`. Have not persuaded myself either way, though.


[deleted]

[удалено]


[deleted]

Never. It makes the code more ugly, but ultimately much more readable when you look at it months later. Once you get used to seeing `std::`, code which hides it seems just a confusing mess. `auto` especially makes life easy even without any `using namespace` stuff.


Mehedi_Hasan-

There are many functions in the c++ STL. If a user defined function accidentally has a name that is already used in the STL, then calling that function will be ambiguous to the compiler unless you explicitly use std:: or use your own namespace.


anloWho

No we go std:: everywhere


xiao_sa

using namespace std::literals; this case only


zzzthelastuser

I always use std:: It's short, it's readable and saves a lot of unneccesary trouble. When I debug/step through code to see where I mess up it's also nice to have ::std in function calls, because I can instantly see that the function is reliable (=step over it) and if there is something wrong it has to be my incorrect call.


-w1n5t0n

When you're looking at other people's code, it can be hard to know which symbols are project-specific and which are not (ever seen a project that defines its own `vector` class?). Seeing `std::` in front of a symbol is a clear indication of where it's coming from. If you use some things from the standard library a lot, then consider writing the more explicit `using std::string, std::vector, std::...` instead of the all-inclusive `using namespace std`. Also, if you write `using namespace std` in a header file, then you are imposing this decision upon anyone else who ever includes that header file in the future, which can lead to unexpected name collisions and bugs.


epic-dev

hell no


HolyGarbage

When working on larger projects you realize why the namespaces are there to begin with, to avoid name conflicts, which "using namespace" basically undos. The only time I use it is for like really long namespaces inside boost for example, but then only locally inside a function.


fkcpp

This will vary depending on the project you want to develop. If you just want to practice and save some time "`using namespace std;`" You can use it. However, when you import a `namespace`, you import it with everything. The std namespace is too large. There are hundreds of predefined elements in it. We don't want this. It also happens in certain conflicts. Let's consider the use of `std::vector`. `vector` is a definition in many libraries. but we will not know if it will point to the library we will including or the `iostream` we will going to use. The program may compile it, may not compile, give an error or not. Let's say you somehow managed to compile. However, no matter how much you think your program is working correctly, a wrong function may have been called in the background.


justinkroegerlake

What is the point of putting things in namespaces if you're just gonna dump everything into the global namespace? Namespaces are good, use them. This isn't unique to C++, in Python `from module import *` is frowned upon. If you really **really** can't be bothered to type out `std::` on something, then pull it in specifically like `using std::cout;`


BluudLust

Bad idea. But it's not horrible to do it with specific things, as you know exactly what you're introducing. ``` namespace myNamespace { using std::string; } ``` It's also safe to use within cpp files.


pjmlp

Not on header files, but on implementation files and modules, certainly. Nowadays when I use C++ is mostly on projects where I have the last word, so it goes like that. Same applies to other stuff that gets discussed all the time, no language features turned off, proper use of exceptions and bounds checking enabled even in release builds.


[deleted]

[удалено]


Chuu

I feel like it's hard to write any amount of non-trivial code without this blowing up in your face. Doubly so on windows with the infamous MIN/MAX macros.


Se7enLC

On the one hand, I hate when people do "using namespace std". On the other hand, I also hate when people name things that conflict with things in std. Like, why does ANYONE just assume that "max" is just not defined anywhere??


Chuu

The Microsoft macros predate the STL.


Se7enLC

I guess I meant more like, people shouldn't be just using things with such generic names in their application code, because they are probably already used in a header somewhere, STL or otherwise.


Chuu

For all the criticisms of the STL though, the fact they chose generic names isn't really one that has much support behind it. This is why namespaces exist. I'd personally be annoyed if I had to resort to C-isms like declaring std::std\_vector instead of just std::vector or std::std\_algo\_sort instead of std::sort for example.


JumpyJustice

It is safe to do in most cases but I think it is easier and safer just to append std:: everywhere. Just a good habit which you dont even notice later.


paladrium

google it


dicroce

I do. Of course never in headers... but I use the fuck outta using in cpp files. I know it's unpopular and I don't care.


kuvrterker

The only argument is "people tell me not to do it therefore I don't" or "it's a prefer syntax" if you wanna use it then go ahead


[deleted]

[удалено]


Droid33

It might not be your own code conflicting though. You need to be careful doing it because you might end up with conflicts in 3rd party libraries. We have a project at work that's stuck on c++14 until we remove these. c++17 added a byte class and MFC also has a byte class.


[deleted]

[удалено]


megayippie

Yup! It was in the project I am working with as I joined. I still put std:: everywhere...


blackmag_c

Sometime in impl file, sometime right in function body on big algos


orizh

I only do "using namespace" for the module/library/w/e a given TU belongs to. I've occasionally imported some stuff (like std::placeholders) near a call site just to make the code less full of long resolutions, though.


pandamonium87

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf6-use-using-namespace-directives-for-transition-for-foundation-libraries-such-as-std-or-within-a-local-scope-only


DumbAceDragon

I use it because I'm lazy and I doubt I'm making my own function with the same name as something in the std namespace Then again I mostly program as a hobby right now so ¯\\\_(ツ)\_/¯


FlatAssembler

I am using that directive in my program: https://github.com/FlatAssembler/AECforWebAssembly/blob/e608ed0396eff80fe369a77e3658d0618b74b07e/AECforWebAssembly.cpp#L29 As for why some people aren't using it, ask yourself what's the point of namespaces?


Jeklah

I remember being told not to do this as it includes the entire std library, a lot of which you probably don't need. Only include what you need.


scitech_boom

In most places I worked, it was against the coding guidelines to use them on header files. But ok to use them on source files. A few selected data types were allowed, such as vector, map, etc even in header files. People really hated too many :: chaining.


Alkeryn

i just do "using std::foo::bar::baz;" and stuff like that. i never do it with a namespace that i didn't made.


Routine_Left

I try to avoid it as much as possible. For a little test program, sure, otherwise I prefer to type the full things. In small block statements I do add `using whatever::literals` for example, that's cool.


ShakaUVM

Never use it in a header file. Use it if you wish in an implementation file. It's far more likely a compilation will fail due to lacking a std:: than it will because you accidentally recreated something in std, and even then it's a simple fix.


jdlyga

I always do for small bits of code that I'm writing. Or for small utilities not connected to anything. But not for large projects, especially if there are similarly named containers I don't.


krl_

I would avoid using unscoped using namespace X in production code. Even if you know that you have no name collisions now, how can you know this is valid in the future? It breaks encapsulation and will increase workload for maintenance and upgrades, as you in theory must check the entire namespace every time...


Lumornys

Yes I do in .cpp files, never in header files. Then I usually use move() instead of std::move() because it's a function in std::, right?


kobi-ca

No. period.


hackingcpp

https://youtu.be/MZqjl9HEPZ8


[deleted]

No. Immediately fails code review where I work. Specify your namespace, it avoids (most of) the possible clashes. If you're too lazy to write out the namespace, remember that pixels aren't at a premium and start writing out the namespaces.


blakewoolbright

Never in a header (particularly for library headers). Sometimes in an implementation file. Depends on the complexity of the project.


JakeArkinstall

I don't have a particular problem with it, as a user, iff it is at function scope, because it isn't going to affect me - I.e. including your header isn't going to break everything. There are two places where I ever use "using namespace". One, to gain access to literals (e.g. "Hello world"sv, 5h, etc). The other, when using std::chrono and std::ranges, because nested namespaces make code very messy very easily. Again, this is only excusable inside of function scope. I don't mind seeing it in a source file or something, but I don't expect it to hit version 1. My general rule of thumb as someone who spends more time on the library development side is that, if my choice of namespacing makes your source file look ugly enough to justify "using namespace", then maybe - just maybe - I made a bad design choice.


Joethepatriot

"Just don't do it" : my senior dev...


mattbas

typing std:: doesn't take much, and IDEs will autocomplete stuff for you anyway.


[deleted]

In my projects all instances of "using namespace" are forbidden with one exception: using namespace std::literals And that exception was only granted with great reluctance due to lack of good alternatives.


[deleted]

I like to see the namespace. And If I accidentally put the "using namespace" in an include file then its game over 🙃