Prefer one of multiple declarations with same name - c++

Suppose I have the following code
namespace A {
int foo();
}
namespace B {
void foo();
}
using namespace A;
using namespace B;
int x = foo(); // error
and I find A::foo really useful, but am not that into B::foo. Is there anything I can do to cause A::foo to be preferred upon subsequent unqualified references to foo? E.g. using A::foo (which in reality has no effect), or unusing B::foo.

The whole point of having a namespace is to isolate names. By using the whole namespace you defy this very reason.
Solution to your problem is to stop using namespace once and for all, and never return to this deplorable tactic.

Related

Invoke a method without using the class name and scope resolution operator

When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std;
How can I do this with a user-defined class or is it impossible. (No pre-processor macro solution please). I tried using this:
#include <iostream>
using namespace std;
namespace std
{
class A
{
public:
static void foo()
{
std::cout << "foo";
}
};
}
int main ()
{
//foo(); does not work
A::foo(); //Only this works
}
Replacing std by any other namespaces also doesn't work.
When invoking a standard method, for example, std::sort(), we just need a namespace and can further simply by using namespace std; How can I do this with a user-defined class [...]
std::sort is a template not a function, but otherwise it is not different from code you can write yourself:
namespace foo {
void bar() {}
}
using namespace foo;
int main() {
bar(); // ok
}
This works for namespaces but not for members of classes (there is using for members of classes to bring something from a base class scope into the derived class scope, but thats a different topic and beyond the scope of the question (no pun intended), it is not what you are asking for here).
In your example there is no reason why foo should be a member of A, hence you should make it a free function (as above). Supposed you didn't write A but you still need to call it without qualifiying the class name you can wrap it in a free function.
Also note that you are not allowed to add something to namespace std. If you do, your code has undefined behavior.
And finally, note that there are good reasons to discourge usage of using some_namespace; altogether. Consider this:
namespace foo1 {
void bar(){}
}
namespace foo2 {
void bar(){}
}
// lots of other code
using namespace foo1;
// lots of other code
int main() {
foo1::bar(); // this is bar from foo1
foo2::bar(); // this is bar from foo2
bar(); // to know which bar this is you have to
// look for any using directive, ie
// it makes your code much harder to read
}
Code is written once but read many times. The 6 extra characters to type pay off in more clear code. See also:
Why is “using namespace std;” considered bad practice?

Can two "using" collide?

So I have to use some members of Boost library and some from the std namespace. Right now, I have using boost::asio::ip::tcp; declared and am calling appropriate members with std:: and for example tcp::iostream server(). Is there any reason why I shouldn't add another using, namely using namespace std; and then call all the std things without std:: prefix? Can these two somehow collide or cause malfunction?
Provided that it is usually considered a bad practice to have using directives that import names from the std namespace (especially when at namespace scope and/or in a header file), because it easily leads to name clashes, consider the following program:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using namespace A;
using namespace B;
foo();
}
How should the compiler resolve the call to foo()? Well, it won't. It is ambiguous, because both A::foo() and B:foo() can now be referred to as the unqualified foo().
If there are entities with the same name in the std namespace and in the global namespace (or in any other namespace for which you have a using directive), ambiguities due to name clashes are likely to arise.
In your specific case, a using directive such as:
using namespace std;
Will be unlikely to clash with the name tcp introduced by your using declaration (notice, that a using declaration imports just one specific name and is, therefore, preferable).
Yet, it is still considered to be poor programming style and you should not do it, regardless of whether you have some other using directive or using declaration already in place.
Yes, they can. The compiler can't resolve the correct namespace in that case. The solution is to use prefixes (for example std::).
You can also put the using namespace keywords inside a function or other block, so the namespace won't be used outside it:
void foo()
{
using namespace ns;
} // ns won't be used after this
Furthermore, namespace usage can be limited to a header:
namespace ns
{
#include "ns.h"
}
However, limiting the namespace to a header is not recommended because it causes problems in many cases.
The other answers do a good job of explaining how ambiguities can be resolved when you have two or more using namespace directives, but it's worth pointing out that the situation is different if you have using declarations that pull in two or more specific names from within namespaces, like this:
namespace A { void foo() { } }
namespace B { void foo() { } }
int main()
{
using A::foo;
using B::foo;
return 0;
}
The above is always a compile error, even though neither foo is ever used. This is because using declarations, as the name suggests, actually declare a name in their enclosing scope to be an alias to a name in some other namespace. This is in contrast to a using namespace directive, which merely makes names available in their enclosing scope without actually declaring any new names.
If you really want to, it's possible to resolve the above code like this:
using fooa = A::foo;
using foob = B::foo;
But using declarations should usually be avoided anyway, because they have some other semantic surprises which can bite you in unexpected, subtle, and sometimes undetectable ways. The exception is using a base class member within a derived class, which is usually OK, though not often necessary.

Nested NameSpaces in C++

I am confused what to do when having nested namespaces and declarations of objects.
I am porting some code that links against a static library that has a few namespaces.
Example of what I am talking about:
namespace ABC {
namespace XYZ {
//STUFF
}
}
In code what do I do to declare an object that is in namespace XYZ?
if I try:
XYZ::ClassA myobject;
or:
ABC::XYZ::ClassA myobject;
or:
ABC::ClassA myobject;
I get
does not name a type
errors, even though ClassA definitely exists.
What is proper here?
It depends on the namespace you already are:
If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA.
If you're in ABC you can skip the ABC and just write XYZ::ClassA.
Also, worth mentioning that if you want to refer to a function which is not in a namespace (or the "root" namespace), you can prefix it by :::
Example:
int foo() { return 1; }
namespace ABC
{
double foo() { return 2.0; }
void bar()
{
foo(); //calls the double version
::foo(); //calls the int version
}
}
If myobject is declared in that namespace and you want to declare it again (for defining it), you do it by prefixing its name, not its type.
ClassA ABC::XYZ::myobject;
If its type is declared in that namespace too, you also need to prefix the name of the type
ABC::XYZ::ClassA ABC::XYZ::myobject;
It's rarely needed to redeclare an object like that. Often the first declaration of an object is also its definition. If you want to first declare the object, you have to do it in that namespace. The following declares and defines "myobject"
namespace ABC {
namespace XYZ {
ClassA myobject;
}
}
If you have defined in object like this, you refer to it by saying ABC::XYZ. You don't have to "declare" that object somehow in order to use it locally
void f() {
ABC::XYZ::myobject = someValue;
// you *can* however use a using-declaration
using ABC::XYZ::myobject;
myobject = someValue;
}

C++ wrapper with same name?

How can I do a wrapper function which calls another function with exactly same name and parameters as the wrapper function itself in global namespace?
For example I have in A.h foo(int bar); and in A.cpp its implementation, and in B.h foo(int bar); and in B.cpp foo(int bar) { foo(bar) }
I want that the B.cpp's foo(bar) calls A.h's foo(int bar), not recursively itself.
How can I do this? I don't want to rename foo.
Update:
A.h is in global namespace and I cannot change it, so I guess using namespaces is not an option?
Update:
Namespaces solve the problem. I did not know you can call global namespace function with ::foo()
does B inherit/implement A at all?
If so you can use
int B::foo(int bar)
{
::foo(bar);
}
to access the foo in the global namespace
or if it does not inherit.. you can use the namespace on B only
namespace B
{
int foo(int bar) { ::foo(bar); }
};
use a namespace
namespace A
{
int foo(int bar);
};
namespace B
{
int foo(int bar) { A::foo(bar); }
};
you can also write using namespace A; in your code but its highly recommended never to write using namespace in a header.
This is the problem that namespaces try to solve. Can you add namespaces to the foo's in question? Then you have a way of resolving this. At any rate, you would hit linker issues if both of them are in global namespace.
You can't do this without using namespaces, changing the name of one of the functions, changing the signature, or making one of them static. The problem is that you can't have 2 functions with the same mangled name. So there needs to be something that makes them different.
As mentioned above, namespace is one solution. However, assuming you have this level of flexibility, why don't you encapsulate this function into classes/structs?

Preferred namespace syntax for source files

Assuming a class called Bar in a namespace called foo, which syntax do you prefer for your source (.cpp/.cc) file?
namespace foo {
...
void Bar::SomeMethod()
{
...
}
} // foo
or
void foo::Bar::SomeMethod()
{
...
}
I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?
I would decline the first (edit : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:
namespace bar {
struct foo { void f(); };
}
namespace baz {
struct foo { void f(); };
}
using namespace bar;
using namespace baz;
void foo::f() { // which foo??
}
Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous.
Personally i would do it like this:
namespace foo {
void Bar::SomeMethod() {
// something in here
}
}
It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo.
The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?
I prefer an option not listed:
namespace foo {
void Bar::SomeMethod()
{
...
}
} // foo namespace
Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win.
I'd rather go for the first case, where namespaces are explicitly marked:
namespace TheNamespace {
void TheClass::TheMethod() {
// code
}
}
The reason is that it is clear from that syntax that TheClass is a class and TheNamespace is a namespace (not so obvious by any other names). If the code were
void TheNamespace::TheClass::TheMethod() {
// code
}
then a reader does not clearly see whether TheNamespace is a namespace, or a class with an inside class by the name of TheClass.
class TheClass1
{
class TheClass2
{
void TheMethod();
}
};
void TheClass1::TheClass2::TheMethod() {
// code
}
I tend to avoid the 'using' statement, and even then the example by litb with two classes in two different namespaces will make both the compiler and the programmer confused and should be avoided.
I think it depends on each case. If it's a 3rd party library that's similar to your own code, and you want to avoid confusion in the code, then specifying the full namespace at each occurance may be beneficial. But other than that, less code is generally better (unless it becomes unclear).