alias: Shortening a Long Name
Let’s learn how an alias can be used for shortening a long name.
We'll cover the following
alias
The alias
keyword assigns aliases to existing names. alias
is different from and unrelated to alias this
.
Shortening a long name
As discussed previously, some names may become too long to be convenient. Let’s consider the following function:
Stack!(Point!double) randomPoints(size_t count) {
auto points = new Stack!(Point!double);
// ...
}
Having to type Stack!(Point!double)
explicitly in multiple places in the program has a number of drawbacks:
-
Longer names can make the code harder to read.
-
It is unnecessary to be reminded at every point that the type is the
Stack
data structure that contains objects of thedouble
instantiations of thePoint
struct template. -
If the requirements of the program change and let’s say
double
needs to be changed toreal
, this change must be carried out in multiple places.
These drawbacks can be eliminated by giving a new name Point
to Stack!(Point!double)
using alias:
alias Points = Stack!(Point!double);
// ...
Points randomPoints(size_t count) {
auto points = new Points;
// ...
}
It may make sense to go further and define two aliases, one taking advantage of the other:
alias PrecisePoint = Point!double;
alias Points = Stack!PrecisePoint;
The syntax of alias
is the following:
alias new_name = existing_name;
After that definition, the new name and the existing name become synonymous; they mean the same thing in the program.
You may encounter the older syntax of this feature in some programs:
// Use of old syntax is discouraged:
alias existing_name new_name;
alias
is also useful when shortening names that otherwise need to be spelled out along with their module names. Let’s assume that the name Queen
appears in two separate modules: chess
and palace
. When both modules are imported, typing merely Queen
would cause a compilation error:
Get hands-on with 1400+ tech skills courses.