xliv
An Overture to C Programmers
};
}
namespace Func {
v
void Jabberwock() {
printf("Burble!");
}
}
Listing 11: Using namespaces to disambiguate functions and types with identical names
In this example,
Jabberwock
the
struct
and
Jabberwock
the function now live
together in frabjous harmony. By placing each element in its own
namespace
—
the
struct
in the
Creature
namespace
u
and
the function in the
Jabberwock
namespace
v
–you can disambiguate which Jabberwock you mean. You can
do such disambiguation in several ways. The simplest is to qualify the name
with its
namespace
, for example:
Creature::Jabberwock x;
Func::Jabberwock();
You can also employ a
using
directive to
import all the names in a
namespace
, so you’d no longer need to use the fully qualified element name.
Listing 12 uses the
Creature
namespace
.
#include
namespace Creature {
struct Jabberwock {
void* tulgey_wood;
int is_galumphing;
};
}
namespace Func {
void Jabberwock() {
printf("Burble!");
}
}
using namespace Creature;
u
int main() {
Jabberwock x;
v
Func::Jabberwock();
}
Listing 12: Employing
using namespace
to refer to a type within the
Creature
namespace
The
using namespace
u
enables you to omit the
namespace
qualification
v
.
But you still need a qualifier on
Func::Jabberwock
, because it isn’t part of the
Creature
namespace
.
An Overture to C Programmers
xlv
Use of a
namespace
is idiomatic C++ and is a zero-overhead abstraction.
Just like the rest of a type’s identifiers, the
namespace
is erased by the com-
piler when emitting assembly code.
In large projects, it’s incredibly helpful
for separating code in different libraries.
Dostları ilə paylaş: