C++ Should I fully qualified my variable type?
-
05-07-2021 - |
Question
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.
Solution
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...
OTHER TIPS
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 theloggingapi
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
andBiz
are actually in different namespaces. Also, it is not going compile, because the compiler will look forBaz
in theloggingapi
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);
}; // ^^^^^^^^^^^^^
}