Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should C++ namespace aliasing be used in header files?

Tags:

c++

namespaces

It's considered bad practice to employ using namespace in C++ headers. Is it similarly a bad idea to use namespace aliasing in a header, and each implementation file should declare the aliases it wishes to use?

Since headers are the places you tend to use fully specified names (since we don't use namespaces in headers), aliases would be useful but they would still propagate though your source when #included.

What is the best practice here? And what is the scope of a namespace alias?

like image 870
Mr. Boy Avatar asked Mar 22 '13 14:03

Mr. Boy


People also ask

Should namespaces be in header files?

Code in header files should always use the fully qualified namespace name. The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members.

Can you use namespace std in a header file?

Since you can't put a namespace using statement at the top level of the header file, you must use a fully qualified name for Standard Library classes or objects in the header file. Thus, expect to see and write lots of std::string, std::cout, std::ostream, etc. in header files.

What is namespace alias?

namespace alias definition Namespace aliases allow the programmer to define an alternate name for a namespace. They are commonly used as a convenient shortcut for long or deeply-nested namespaces.

What is the difference between namespace and header file?

A header file is a file that is intended to be included by source files. They typically contain declarations of certain classes and functions. A namespace enables code to categorize identifiers. That is, classes, functions, etc.


1 Answers

If you put a namespace alias into your header this alias will become part of your (public) API.

Sometimes this technique is used to do ABI compatible versioning (or at least to make breakage visible) like this:

namespace lib_v1 { ... }
namespace lib_v2 { ... }
namespace lib = lib_v2;

or more commonly:

namespace lib {
   namespace v1 {}
   namespace v2 {}
   using namespace v2;
}

On the other hand if you do it just to save some typing it is probably not such a good idea. (Still much better than using a using directive)

like image 143
Fabio Fracassi Avatar answered Sep 28 '22 10:09

Fabio Fracassi