D
D
Daniel Demidko2018-04-12 03:42:55
C++ / C#
Daniel Demidko, 2018-04-12 03:42:55

How does operator>> get into the global namespace?

If I do not import the namespace std, but specify the types and functions I need explicitly, through the prefix std::, then how do they end up in the global namespace? Let me explain with a code examplestd::operator>>std::operator<<

#include <iostream>
int main()
{
    int size;
    // Как? Ведь std::operator>> определён в std, а мы его не импортировали
    std::cin >> size;
}

And for comparison
namespace My
{
    std::istream &operator>>(std::istream &stream, int &n) { /*...*/}
}
int main()
{
    int size;
    // Как мы видим operator>> из My не влияет пока мы
    //явно его не импортируем в глобальное пространство имён
    std::cin >> size;
}

What's the magic with std ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Shatunov, 2018-04-12
@DanielDemidko

You should familiarize yourself with the concept of ADL .
Those. any external operator overload for some type defined in that type's namespace is part of that type's interface and is available through ADL.
Friend functions are also available through ADL if they are defined at the place of the friend declaration and do not have a previous declaration.
As a result, operator>>no magical powers are transferred to the global namespace. It is simply located on ADL, tk. is properly implemented and is part of the corresponding type's interface.

M
maaGames, 2018-04-12
@maaGames

// How? After all, std::operator>> is defined in std, and we didn't import it
std::cin >> size;
It is not defined in std, but as an inline class method basic_istream (file istream):
basic_istream& __CLR_OR_THIS_CALL operator>>(int& _Val);
It turns out that an external function is first searched, if not found, then the class method is used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question