How to properly use namespaces to avoid name collision? - c++

I'm a bit confused concerning proper usage of C++ namespaces. It is clear for me how they can help to avoid conflicts (name collision), but it is not clear anymore when it comes to the using keyword. I mean, suppose I have a part of my code that I put into a namespace, and create a class, say
namespace my
{
class vector { ... };
}
Of course, when I use it, I wouldn't like to type my::vector all the time, so I'd like using namespace my. However, I could eventually need something from the std namespace, and then I want using namespace std at the same time, but this will bring me back to the initial name collision problem.
I know that it is possible to "import" only the functionality that I need, like using std::set, but in this case it seems natural to import both the standard namespace std and my namespace completely as I'd use both of them all the time.
Does this mean that even when I use namespaces I should still think about giving non-common names to my types? Or is using namespace a mistake and I should always type my::vector instead? Thanks.
Well, I should probably clarify that it is more a question of readability than typing. Lots of :: everywhere look really weird to me. I know it's a question of taste and habits, but nevertheless.

Of course, when I use it, I wouldn't like to type my::vector all the time, so I'd like using namespace my. However, I could eventually need something from the std namespace, and then I want using namespace std at the same time, but this will bring me back to the initial name collision problem.
Yes, it would bring you back to the initial name collision problem. This is why you should use using namespace ...; directives sparingly, and only in source files, never in headers.
Does this mean that even when I use namespaces I should still think about giving non-common names to my types?
No, you shouldn't. Namespaces were invented precisely to avoid this.
Or is using namespace a mistake and I should always type my::vector instead?
You can, if you want to, use the using namespace ...; or using ...; directives until you get conflicts. This means that when you do have conflicts, you'll end up writing "unnatural" code by explicitly quallifying names in some places.
In practice, when you're dealing with short namespace names (i.e. std), you can just type them explicitly all the time. After a week or so, you won't even notice you're typing it anymore.

If your code uses both std::vector and my::vector, then always writing the names in full is the best option.

Why bother putting it in a namespace in the first place, if you are immediately opening up the namespace again? You could just as well have put the class in the global namespace!
It would also be very confusing for people who didn't notice the using directive at the top of your file, that vector isn't std::vector. That in itself is a reason for writing my::vector!
To me, seeing names like std::vector and std::list actually improves readability, because I immediately know what those names mean.

Related

How to check if a variable or function exists in std?(in c++)

I'm using std in my code(using namespace std)(I know it's not so good & should be avoided) and then I wondered which names are available to be used for variables or functions and which are already occupied so I searched for the list of the std variables & functions but I didn't find it.
PS. my code is actually a homework so there is no expanding dream and also cause it's a homework I'm expected to use std ( :| )(and even if I'm not I'm just curious about the answer). so my problem is what are the vars & funcs that are existing in std right now.
There is no definitive list of names inside std - it can always be expanded, and was created exactly for that purpose. Therefore, stop using the namespace once and for all.
In other words, C++ standard prescribes what names have to be there, but by no means it limits the overall names set to those prescribed. Implementations often put a lot of other helper functions or classess into this namespace.
As the others suggested, stop using namespace std - this is bad practice.
I'd also suggest that you stop using any namespace. This way your code reads better, you avoid shadowing things and name clashes and, most importantly, you are always in charge of your codebase: you know where the things you use come from and what their broader scope/purpose may be. This can make your code more maintainable: for example it's easier to see what headers are not in use. what kind of functions are just auxillary/internal etc.
This is primarily a matter of taste, but I'd further suggest that you use namespaces or verbose descriptive names yourself (at least for those objects that don't have very short scope). All contemporary IDE's offer autocompletion so you won't even have to type this more than once. In my code I use things such as:
bool has_the_loader_finished;
bool should_the_program_quit;
void helper::setup::setup_animation();
all the time. This way a. I don't really need many comments in my code, most of the things are self-explanatory so I reserve comments only for special things and b. I'm sure that there will be no name clashes and c. I don't have to spent time trying to debug/refactor code where I no longer remember what things such as
int i;
bool flag;
void setup();
stand for..
There are of course cases where using is intuitive, such as:
using std::placeholders
ExampleFunction f = std::bind(&Object::hello, &instance,_1); // instead of std::placeholders::_1
using namespace std::chrono_literals;
auto halfmin = 30s; //instead of std::chrono_literals::30s
using ms = std::chrono::milliseconds; // this is an alias basically
Good practice, however, is to always a. restrict using to those particular things you plan to use, e.g.: using std::placeholders rather than using std b. use aliases or typedefs and c. limit the scope of using (and typedefs/aliases) as much as you can e.g.:
int someFunction() {
using namespace std;
// no more than a 20-30 lines of code here
}
or
// someSmallFile.cpp
using namespace std; // this is valid in the body of this file only
Finally, NEVER use using namespace in header files. This will expose the internals of this namespace to all translation units that include that file and without your clients necessarily knowing about it...

C++ Name Resolution

I'm wondering a bit about the namespace and using in C++ basically I would like to know the differences and figure out how to use it in the best way.
As I see it there are (at least) three ways to resolve a class name and I am not sure how to choose among them:
using namespace <namespace>
using <namespace>::<what_to_use>
<namespace>::<what_to_use> <use_it>
I would like to know the advantages especially if there are performance involved in one or the other way, if it's just syntactical and a matter of preference or if there are other things I haven't considered regarding this.
First is an using namespace directive, it brings all the symbol names from the specified namespace in your current namespace, irrespective of whether you need/use them. Certainly undesirable.
Second is using namespace declaration. It only brings the specified symbol name in your current namespace. Advantage is you don't have to type the fully qualified name everytime.
Third is an fully qualified names of the symbol. Disadvantage is that you have to type the fully qualified name everywhere you use the symbol.
Clearly, Second & Third are the more suitable ones. There is no performance difference in either of them. The only difference is the amount of characters you type in. Simply, choose either depending on what your coding standard specifies.
EDIT:
As #Jerry points out, using declaration in combination with ADL(Argument dependent lookup) can lead to undesirable effects.
You can find a detailed explanation in one of my answers:
Detailed explanation on how Koenig lookup works with namespaces and why its a good thing?
under the section,
Why the criticism of Koenig Algorithm?
There is one (admittedly, somewhat uncommon) situation in which the form you use really can make a difference, and the form you want to use is using namespace foo, and it's most commonly applied to the std namespace (i.e., where you write using namespace std;.
The most obvious example is that you're writing a sort for a user-defined type. It's possible that this will be applied to a type for which the user has also defined their own swap.
You're stuck with a situation where you want to use their swap if they've defined one, but use std::swap if they haven't defined one. If you use std::swap directly in your code, then you'll end up using std::swap even if the type has a swap of its own defined. Conversely, your code will fail to compile if you directly specify a swap specifically for the type, and none has been supplied.
To get around this, you do something like:
using namespace std;
template <class Iter>
void my_sort(Iter first, Iter last) {
// ...
if (*last < *first)
swap(*first, *last);
}
This will find the swap specifically for the type being compared (i.e., a swap defined in the same namespace as that type), if there is one (via argument dependent lookup), and std::swap if none is defined for the type (via the using namespace std;).
This can have an impact on performance -- if they've written a swap specifically for their type, you can generally expect that it's because by doing so, they can provide better performance. That means that explicitly specifying std::swap may work, but will probably lead to inferior performance.
Otherwise, it's almost entirely a matter of convenience and readability -- I mostly prefer giving the full names (e.g., std::swap) except in a situation like above, where (at the time that I'm writing the code) either of at least two possibilities might be preferred, and I want to give the compiler sufficient leeway to pick the right one.
The other time I find using declarations/directives useful is when namespaces get really deeply nested. Boost (for one obvious example) has some names that would be way too long for convenient use if you used the fully qualified name every time. This was especially true for the (now, thankfully, mostly obsolete) Boost Lambda library, where you used placeholders like _1, that would have ended up as something like boost::lambda::placeholders::_1 (but I'm going from memory, so that's probably at least partly wrong) if you insisted on using a fully qualified name. That would have defeated a large part of the purpose of using the lambda library in the first place.
There's no performance gain or penalty whatsoever. All calls and variables are resolved at compile-time.
The choice between the three is somewhat subjective. Yes, using namespace <ns>; is sometimes frowned upon for polluting the global namespace, but I think it's safe to use for small files.
I tend to use the second one for testing purposes where I'm expecting conflicts, but I'd just remove it afterwards. This can get messier because you can end up with combinations of both qualified and un-qualified names:
vector<std::string> x;
because you have a using std::vector; at the top, but not a using std::string;.
I preffer the third.
There is zero impact on performance of your code, this is purely a compile-time thing. It might (in theory) have some impact on compilation times, but I doubt that would ever reach measurable proportions.
using namespace std (or any other namespace for that matter) is definitely to be avoided in header files, which can be included anywhere and introducing the symbols in them could result in ambiguities.
Generally, namespaces exist to avoid name clashes and using namespace destroys this purpose. So does using the_namespace::some_id, to a lesser degree. There is no definite answer to your question, but I generally follow these rules:
Never put using namespace in a header file.
Avoid using namespace and using, unless it can save tremendous amounts of typing. Use namespace aliases if necessary (that is, namespace abbrv = some_really::long_and::nested_namespace;).
Try to limit the scope of using: you can put this into functions and blocks as well as namespace scope. That is, if you have a logging function in your .cpp file, put using std::cout; and using std::endl; (or whatever you're using) into the function body, not into the file scope.
Main reason is that it could lead to ambiguities (both for compiler and for human reader) and it can also slowdown the compilation itself (but that's not that big problem as the first thing)

Are all using directives viewed the same way as using namespace std?

I've easily gotten myself into the habit of prefixing standard identifiers with std:: instead of sticking in a using namespace std;. However, I've started getting into C# and I've noticed that it's very normal to add in whatever using directives are necessary, i.e., you'd see:
using System;
Console.Write("foo");
instead of:
System.Console.Write("foo");
Apparently, as I found out from a C# question on this topic, that usage comes from the fact that individual system namespaces in C# are much, much smaller than std is in C++, and therefore eliminates the problems associated with name clashes, as there is much less likelihood (and you can just find-replace it with a fully qualified name if a library updates with a name-clash), and eliminates the problems associated with a crapload of Intellisense options appearing, as the namespaces are small enough to handle.
The question, then, is that if these are the standing reasons to make use of using directives in C#, is the same true for C++? Is it generally acceptable to apply this to smaller third-party namespaces, as well as your own smaller namespaces?
Now I realize that this might cause a bit of controversy, I want to take this moment to ask that it doesn't turn into an argument. A good answer should include a basis, i.e., advantages or disadvantages, and how using one way over the other really makes a worthwhile difference.
The reason I ask this is to clear up the issue, and possibly remove the notion that using directives in C++ have to be a bad thing. Sure longer namespace names can be cut down with a namespace alias if necessary, and fully qualified names can still be used if needed, but sometimes a using directive greatly eases accessing some members such as user-defined literal operators, which, to my knowledge, have no form of ADL, meaning that you either have to use a using directive, or call the operator method by the function syntax, defeating the whole purpose of using the operator in the first place.
For example, I had a namespace (that includes a structure representing a keyboard key, along with a literal suffix as a readable alternate means of access:
"caps lock"_key.disable();
The problem here is that unless you have previously inserted using namespace Whatever; or using Whatever::operator"" _key;, the code won't compile, which is bad news for the user.
Using directives have obvious problems when std is involved or when used in such a way in a header that they bring unwanted extras for the user of that header, but is it justified to use them for other namespaces when contained within a smaller scope than whatever includes a header? The keystrokes saved from not having to type each qualifier each time do add up, and with today's Intellisense capabilities, finding out which namespace an unqualified identifier belongs to is as easy as mousing over it.
I think the rules about using declarations in C++ are rather simple:
NEVER write "using namespace anything;" in the global scope of a header, especially one that is likely to be reused by other programs (e.g. when writing a library). It pollutes the global scope of all subsequent headers with the symbols of this namespace, which defeats the entire purpose of namespaces, and can create unforeseen name clashes later on.
In the .cpp files and inner scopes of headers (e.g. inline function scopes), you can be "using" whatever namespaces you want, as it won't affect any other file. Just do whatever is more convenient for you and try to be reasonably consistent within a project.
EDIT: for the _key problem, simply define this operator in its own namespace and tell users to import it. This way they won't need to type out the operator declaration.
namespace something {
class key { ... };
}
namespace key_suffix {
something::key operator"" _key() { ... }
}
// user code
void some_function() {
using namespace key_suffix;
"caps lock"_key.doSomething();
}

Why is std:: used by experienced coders rather than using namespace std;? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is 'using namespace std;' considered a bad practice in C++?
The other day when I asked a question someone replied saying if someone asks a question, show them the right way to do it instead of using namespace std; which I thought was a bit weird, as using namespace std; is way easier, But I guess I'm failing right now as I am a 'beginner' coder and you guys know better.
So I guess my question is:
Why std:: instead of using namespace std;?
Thanks.
From C++ FAQ:
Should I use using namespace std in my code?
Probably not.
People don't like typing std:: over
and over, and they discover that
using namespace std lets the compiler see
any std name, even if unqualified. The
fly in that ointment is that it lets
the compiler see any std name, even
the ones you didn't think about. In
other words, it can create name
conflicts and ambiguities.
https://isocpp.org/wiki/faq/coding-standards#using-namespace-std
Simply put, you are less likely to use the wrong types or functions by mistake, or name conflicts. Say you are using your own math library, plus std, and declare using both of them, in some arbitrary order. Now, they both define function pow. Which pow are you using when you invoke pow? I think it is worth the extra typing.
I don't think it's the case that more experienced programmers use explicit namespaces, see e.g. Do you prefer explicit namespaces or 'using' in C++?
Note however that you should never import namespaces in header files and that in some cases explicit namespaces are clearer, for example with the functions std::min() and std::max()
I think it is some what a preference thing. Some people like to see the explicit namespaces when using the classes.
One exception is I never to use a using namespace std in a header file. As this can unexpectedly change the behaviour of a class that is using this header file.
Experienced programmers use whatever solves their problems and avoid whatever creates new problems.
Thus they avoid header-file-level using-directives for obvious reason.
And they try to avoid full qualification of names inside their source files.
Minor point is that it's not elegant to write more code when less code suffice without good reason. Major point is turning off ADL.
What are these good reasons? Sometimes you explicitly want turning off ADL. Sometime you want to disambiguate.
So following are ok: 1) function-level using-directives and using-declarations inside functions' implementations; 2) source-file-level using-declarations inside source files; 3) (sometimes) source-file-level using-directives.
Namespace(s) are additional qualifiers for our variables. Lets say we have 'string' defined in std and now if we define a 'string' in mynamespacealso.
Now, if I write using namespace std;at the top of a file, then from there onwards a string becomes ambiguous for a compiler.
One can however take a middle approach, of strictly not having using namespace std;in a header(.h) file, since others might want to use your class and can get conflicts. While for an implementation (.cxx) file, you can be careful to use it if you are sure there won't be any conflicts.

How to resolve a naming conflict between two libraries in C++?

I am using two large libraries (GUI & network) and I can happily do
using namespace FirstLib;
using namespace SecondLib;
Except for 1 single class called Foobar where names clash.
I my code, I do not use FirstLib::Foobar. Is there a way to say "in my code, whenever you see Foobar, think SecondLib::Foobar ?
using namespace is evil! Namespaces were made to prevent such problems as you have! But that said, try:
using namespace FirstLib;
using namespace SecondLib;
using SecondLib::Foobar;
or even (for some compilers):
using namespace FirstLib;
using namespace SecondLib;
typedef SecondLib::Foobar Foobar;
It's strange nobody suggested to replace the full namespace use by the list of used class names. This solution is even in the C++faq (where I should have thought to look first).
If we cannot say
include all FirstLib, but remove SecondLib::Foobar
We can use using-declarations of the exact elements we need:
using FirstLib::Boids;
using FirstLib::Life;
// no using FirstLib::Foobar...
You've basically answered your own question. You must explicitly say which class you want to use, so you must do SecondLib::Foobar whenever you use that class.
You have to pick one of these namespaces and get rid of the 'using', and explicitly call out all the class names. C# has a way around this, but C++ does not afaik...
I don't think there's a way of excluding names. You either bring in the whole lot, or each one individually. Even when you bring in the whole lot, you can always disambiguate conflicting names by qualifying them fully.
However, you could use typedef to rename the offending class:
typedef Lib2::FooBar FooBaz;
And I guess, with a conflicting function, you could use a function pointer to "rename" the conflicting one.
I guess it's kind of a non-solution. I can understand the occasional motivation to use using declarations - sometimes there are indeed many different names that you'll use all over the place - but if just one is conflicting: be explicit. It would be confusing to anyone familiar with the libraries anyway, seeing that both namespaces are imported.
Also, using declarations respect scope: you can make one namespace visible in one function, but not the other namespace - assuming you don't even use it in that function.
Have you tried:
using SecondLib::Foobar;
?
If you load all elements from both namespace to current scope by use of using namespace directove:
using namespace FirstLib;
using namespace SecondLib;
and there is potential that some of the names in those namespace may clash, then you need to tell compiler explicitly which of the element you want to use, in current scope, by use of using declaration:
using SecondLib::Foobar;
As the C++ standard says:
7.3.3 The using declaration
1 A using-declaration introduces a
name into the declarative region in
which the using-declaration appears.
That name is a synonym for the name of
some entity declared elsewhere.
This line requests compiler to think SecondLib::Foobar whenever it sees Foobar for the rest of current scope in which the using declaration was used.
The using directive and declaration is very helpful, but they may cause problems as the one you're dealing with. So, it's a good idea to narrow use of any form of using to minimal scope possible. You can use the directive using namespace in scope of other namespace
namespace MyApp {
using namespace ::SecondLib;
}
or even a function. The same applies to using declaration. So, it's a good idea to narrow the scope of use of any of them:
void foo()
{
::SecondLib::Foobar fb;
}
It may seem tedious, but it is only when you type, though you most likely use intellisense-enabled editor, so cost is really small, but benefits are large - no confusions, readable code, no compilation issues.
It's also a very good idea to NOT to use using namespace in header scope. See Header files usage - Best practices - C++
My own tip: do use full qualification whenever you need to use any of these types