How to resolve a naming conflict between two libraries in C++? - 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

Related

multiple "using namespace" in a line?

I searched but I could not find related question.
Please correct me if I'm wrong.
In my project I use the following:
using namespace std;
using namespace sf;
I want it to be like below.
using namespace std, sf;
Thanks in advance!
This syntax is not supported, so you'll have to keep declaring multiple using statements.
In general, though, it's considered best practice to avoid declaring using namespace at all - definitely not in headers, and preferably in the inner-most scope possible (as to not pollute too much scope with unwanted symbols.
I want it to be like below.
using namespace std, sf;
The syntax you're after is simply not supported by the current c++ standard.
Besides it is discouraged to import whole namespaces (at least not in header files), you may sent a request to the c++ standards committee, and see if they like to support that.
The general advice is that you should only
either specify exact classes you're using in your translation unit (to save typing) like using std::cout = co;
or to make everything clear by explicitly using fully qualified identifiers everywhere like std::cout, std::endl, etc.
The latter way is the most readable and best IMO.

Dealing with painfully long namespace names in headers

Is there anything that can be done about looong symbols that need to be referenced in header files, e.g. ABDEFGHIJ::ZXCBVB::AWEDADSDEM::GFGBKGDF::Tools::Item? I know in header files you aren't supposed to using using because it messes up anybody who includes it.
The only working feature that cleans up after itself that I can even think of would be #define+#undef but that seems terrible.
Is there a new feature that solves this that I'm not aware of? I'm also interested in any popular proposals. Maybe using with a bracketed block syntax, to let me restrict the effect to just my header...?
It's not good practice to have a using namespace using directive at global scope in a header file. There are a number of less drastic things you can do that are fairly benign however.
Inside an inline or template function in a header, you can use a using directive without affecting anyone else. This saves you having to qualify all the names in a non-trivial function body.
As Maksim Solovjov suggests, you can use namespace aliases to cut down on typing, with the caveat that a namespace alias at global scope will introduce that alias to anyone including your header so that may not be desirable.
C++11 introduced type aliases and alias templates which can be used in a header at class scope, function scope or namespace scope (you may still want to avoid using them at global scope) to give a shorter name to types. This is particularly useful when dealing with template types with long names like e.g. std::map<std::string, std::vector<std::function<float(float)>>>
C++11 and 14 type deduction through the auto keyword can greatly reduce the need to name long types in headers, whether function return types, local variables or parameters to lambdas.
C++11 decltype can also be useful to avoid saying the names of long types in certain situations.
Here is what I feel.
First of all you should create your own namespaces. Then you can draw in other namespace symbols without polluting the global namespace.
If the namespace you are accessing is truly massive (like std) then I would always either use the std:: qualifier or declare the types explicitly:
namespace my_project {
std::string s; // qualify
// or declare specific types
using std::string;
} // my_project
If the namespace is from your own project or a relatively small library then I see no reason not to inject the whole namespace into your own (never into the global namespace).
namespace my_project {
using namespace xmltools; // never do this in global namespace
// use without prefix here
} // my_project
The key is to use your own namespaces. Then what you do inside them will have less affect on people using your headers.
I think the main point is to remember that if someone injects the symbols from your namespace into their own they should not be surprised by what it contains.
So if my library builds on another library it may be normal for my library to contain the type symbols from the other library and someone injecting my namespace into theirs would also expect that.
You can have namespace aliases:
namespace fbz = foo::bar::baz;
However, you would introduce fbz to every file that includes your header.

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();
}

How to properly use namespaces to avoid name collision?

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.

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...