jeudi 4 février 2021

confusion about C++ name lookup

According to my knowledge, the name in a nested scope will hide the same name in the enclosing scope, just like what shows below:

namespace ttt {
    class A {};

    void test(const A&, int)
    {
        cout << "ttt::test()" << endl;
    }
}

void test(const ttt::A&, int)
{
    cout << "global::test()" << endl;
}

int main()
{
    void test(const ttt::A&, int);
    ttt::A a;
    test(a, 1);
}

the declaration of void test(const ttt::A&, int); in the main function hides the same name which is in the namespace ttt, so the console prints global::test()(Tested in Visual Studio 2019)

However, when I try the code below:

std::ostream& operator<< (std::ostream& os, const string& str)
{
    os << "global::operator" << endl;
    return os;
}

int main()
{
    std::ostream& operator<< (std::ostream & os, const string & str);
    string a = "STD's operator";

    cout << a << "STD's operator" << endl;
}

I try to overload the << operator which is a template defined in STL with my own version of <<. According to the first example, the declaration of operator<< in main should hide the STL defined version of <<, then the desired output should be

global::operator
global::operator
global::operator

or a compile error, since I don't know whether endl can be converted to string. however, the result of the program is:

global::operator
STD's operator

So the second and the last << in the statement cout << a << "STD's operator" << endl; invokes the STL's <<, not the overloaded one define by me. Shouldn't the << already be hidden by the declaration std::ostream& operator<< (std::ostream & os, const string & str); in main ?

Aucun commentaire:

Enregistrer un commentaire