Why I have to write std::cout and not also std::<<

后端 未结 3 1211
孤街浪徒
孤街浪徒 2020-12-23 23:59

Why do I have to write std::cout and not also std::<< in a line of code like this:

#include 

int main() {
           


        
3条回答
  •  误落风尘
    2020-12-24 00:54

    In std::cout << "Hello, world!"; //calls std:::operator <<

    This is achieved with Argument-dependent name lookup (ADL, aka Koenig Lookup)

    Although we have only one std qualifier but there are two things that comes up from std namespace

    • cout
    • <<

    Without ADL, (Koenig Lookup)

    std::cout std:: << "Hello World" ;//this won't compile

    In order to compile it, we need to use it more uglier form

    std::operator<<(std::cout, "Hello, world!");

    So to avoid such ugly syntax we must appreciate Koenig Lookup :)

提交回复
热议问题