Using-Directive Versus Using-Declaration
Using a using-directive to import all the names wholesale is not the same as using multiple using-declarations. It's more like the mass
application of a scope resolution operator. When you use a using-declaration, it is as if the name is declared at the location of the
using-declaration. If a particular name already is declared in a function, you can't import the same name with a using-declaration. When
you use a using-directive, however, name resolution takes place as if you declared the names in the smallest declarative region containing
both the using-declaration and the namespace itself.
Remember
Suppose a namespace and a declarative region both define the same name. If you attempt to use a using-declaration to bring the namespace
name into the declarative region, the two names conflict, and you get an error. If you use a using-directive to bring the namespace name into
the declarative region, the local version of the name hides the namespace version.
Unnamed Namespaces
You can create an unnamed namespace by omitting the namespace name:
namespace // unnamed namespace
{
int ice;
int bandycoot;
}
This behaves as if it were followed by a using-directive; that is, the names declared in this namespace are in potential scope until the end
of the declarative region containing the unnamed namespace. In this respect, they are like global variables. However, because the namespace has
no name, you can't explicitly use a using-directive or using-declaration to make the names available elsewhere. In particular, you can't use names
from an unnamed namespace in a file other than the one containing the namespace declaration. This provides an alternative to using static variables
with internal linkage. Indeed, the C++ standard deprecates the use of the keyword static in namespaces and global scope. ("Deprecate" is a term
the standard uses to indicate practices that currently are valid but most likely will be rendered invalid by future revisions of the standard.)
Suppose, for example, you have this code:
static int counts; // static storage, internal linkage
int other();
int main()
{
}
int other()
{
}
The intent of the standard is that you should do this instead:
namespace
{
int counts; // static storage, internal linkage
}
int other();
int main()
{
}
int other()
{
}
April 22th Wednesday (四月 二十二日 水曜日)
最新推荐文章于 2022-02-25 21:57:21 发布