using
DeclarationsUp to now, our programs have explicitly indicated that each library name we use is in the std
namespace. For example, to read from the standard input, we write std::cin
. These names use the scope operator (::
) (§ 1.2, p. 8), which says that the compiler should look in the scope of the left-hand operand for the name of the right-hand operand. Thus, std::cin
says that we want to use the name cin
from the namespace std
.
Referring to library names with this notation can be cumbersome. Fortunately, there are easier ways to use namespace members. The safest way is a using
declaration. § 18.2.2 (p. 793) covers another way to use names from a namespace.
A using
declaration lets us use a name from a namespace without qualifying the name with a namespace_name::
prefix. A using
declaration has the form
using namespace::name;
Once the using
declaration has been made, we can access name directly:
#include <iostream>
// using declaration; when we use the name cin, we get the one from the namespace std
using std::cin;
int main()
{
int i;
cin >> i; // ok: cin is a synonym for std::cin
cout << i; // error: no using declaration; we must use the full name
std::cout << i; // ok: explicitly use cout from namepsace std
return 0;
}