Consider the following two statements:
namespace foo = bar;
and
namespace foo {
using namespace bar;
}
Are those two statements equivalent, or are there some subtle differences I'm not aware of?
(Please note that this is not a question about coding style - I'm just interested in C++ parsing).
namespace foo=bar;
This does not affect any name lookup rules. The only affect is to make 'foo' an alias to 'bar'. for example:
namespace bar
{
void b();
}
void f () {
bar::b (); // Call 'b' in bar
foo::b (); // 'foo' is an alias to 'bar' so calls same function
}
The following does change lookup rules
namespace NS
{
namespace bar
{
}
namespace foo {
using namespace bar;
void f () {
++i;
}
}
}
When lookup takes place for 'i', 'foo' will be searched first, then 'NS' then 'bar'.
As you are importing a namespace into another, then yes, it should be equal in that respect. However, the second one also allows for other code to be placed within, so you can also put things which are not part of namespace foo within it. The former merely creates an alias.
Related
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?
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.
I am trying to write lines of code fitting under 80 columns maximum. Thus, I wonder if fully qualifying my variable type is really mandatory ? Assuming the following implementation:
//Baz.h
namespace loggingapi {
namespace attributes {
class Baz {};
}} // namespaces
// Bar.h
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(Baz* b);
};
} // namespaces
To declare my function parameter type, there are multiple ways ?
a) int f(Baz* b);
b) OR int f(attributes::Baz* b);
c) OR int f(loggingapi::attributes::Baz* b);
d) OR int f(::loggingapi::attributes::Baz* b);
In the list above, which definition(s) is/are clearer/ambiguous for the compilers ?
NOTE: You must assume the namespace/parameter/class/function names CANNOT be shortened in the following implementation.
Variant e ?
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
typedef attributes::Baz Baz;
// C++ 11 alternative
// using Baz = attributes::Baz;
int f(Baz* b);
}
} // namespaces
Do not forget what aliasing can do for you...
I would go with the b) variant. My reasons are as follows:
We assume that the developer knows in what namespace he is now. So when looking at the class Biz, the developer should know that this class is in the loggingapi namespace, therefore, there's no need to explicitly state it.
The a) variant, on the other hand, isn't clear enough, because we should indicate that Baz and Biz are actually in different namespaces. Also, it is not going compile, because the compiler will look for Baz in the loggingapi namespace, and it isn't there.
You should choose (b). It's more flexible. If you decide to move or (gasp) cut and paste f and it's related types to a new namespace or project then using (b) ensures that the structure of the declarations remains internally consistent.
You can choose to add, remove or rename outer wrapping namespaces without affecting the enclosed code.
In h-file it is better to use fully qualified names, to prevent possible ambiguity in a client code. In .cpp file you can use short notation, if you prefer this, as long as there is no name clash.
If a compiler has some ambiguity it will definitely report an error.
I believe the question should be with respect to the human reader, which is quite subjective.
The naming convention depends on
Pre-decided coding style
Where you are declaring the function f()
There is no clear choice over another. I would prefer that, if both entities are belonging to same namespace then I will omit at least that part from the name:
namespace loggingapi {
namespace attributes {
class Baz; // forward declare Baz.
}
class Biz {
int f(attribute::Baz* b);
}; // ^^^^^^^^^^^^^
}
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;
}
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).