c++namespacesunqualified-name

Is Bjarne implying that using-directives make it impossible to qualify names in that namespace later?


Am I misunderstanding, Bjarne's 2nd edition Chapter 3 of A Tour of C++ section on namespaces as it seems to imply that once a using-directive is used, we can't qualify it?

By using a using-directive, we lose the ability to selectively use names from that namespace, so this facility should be used carefully, usually for a library that’s pervasive in an application (e.g., std) or during a transition for an application that didn’t use namespaces.

If this isn't it, what does this citation mean? I didn't see it posted in the 2nd errata. I tested this out with this code and it compiled and ran without any issue.

#include <iostream>
using namespace std;

int main()
{
    std::cout << "works\n";
}

Solution

  • It is not about using qualified names, but unqualified ones.

    For example, if you use using namespace std; with the intention to only use cout unqualified, then you still did import all other names from std as well and they will all be considered for uses of unqualified names. You can't selectively import only some names from std with the statement and you need to be aware of that.

    For example:

    #include<iostream>
    
    using namespace std;
    
    void move(long i)
    {
        cout << "move(" << i << ")\n";
    }
    
    int main()
    {
        move(42);
    }
    

    Since C++11 this program may or may not print move(42), because there is a std::move function in the standard library that would be a better overload resolution match for move(42) if its declaration is reachable from the call. And because of using namespace std; this std::move library name is also made available to unqualified lookup, even if this is not your intention.

    Whether the declaration is reachable or not is unspecified because <iostream> is not guaranteed to declare it, but also isn't required not to declare it.