Namespace alias
- C++ course
- Beginner
- Lesson 110/116
- 5 min
Learn short names with namespace aliases.
Namespace alias
To shorten long namespace chains, you use an alias. It is written as namespace short = long_name;; this frees you from writing the long chain repeatedly.
namespace short_ns = app::util;
int n = short_ns::helper();Here short_ns becomes a short name for the app::util namespace. Calls now use the form short_ns::helper(). This especially improves readability with multi-level namespaces.
Alias usage examples
Aliases are especially useful for multi-level standard library namespaces. For example, a long name like std::chrono::milliseconds can be shortened with namespace chr = std::chrono; and called as chr::milliseconds.
This both improves readability and allows single-point updates if a name changes. Teams usually agree on common abbreviations and use them consistently across the project.
Practice Use an alias for a short name
Define namespace app { namespace util { int helper() { return 7; } } }. Define an alias with namespace short_ns = app::util;. In main, call int n = short_ns::helper();, print with cout << n << endl;.
Starter code
#include <iostream>
using namespace std;
// Define app and util namespaces
// Define the short_ns alias
int main() {
// call helper with the alias and print
return 0;
}Sample solution
#include <iostream>
using namespace std;
namespace app {
namespace util {
int helper() { return 7; }
}
}
namespace short_ns = app::util;
int main() {
int n = short_ns::helper();
cout << n << endl;
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each expression with its purpose
| Term | Meaning |
|---|---|
namespace x = y |
gives a short name |
x::helper() |
call with short name |
app::util::helper |
full call |
2 What does namespace short_ns = app::util; do?
- Removes app::util
- Defines a new namespace
- Gives a short name for app::util Correct answer
- It is a using directive
Explanation: short_ns is now a short name for app::util.
3 Fill in the blank: alias definition
namespace short_ns ____ app::util;
namespace short_ns = app::util;
Explanation: The = marks the alias assignment.