Search code examples
c++c++17void-pointersnullptr

`cout<<nullptr` giving error though `nullptr` has type `nullptr_t` from C++17


Code-1

#include <iostream>

int main()
{
    std::cout << nullptr;
    return 0;
}

Output

Error: Use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream<char>') and 'nullptr_t')

Even there is specific type for nullptr why it is showing error. But

Code-2

#include <iostream>

int main()
{
    std::cout << (void*)nullptr;
    return 0;
}

Output

0

Works fine. Why it work with void* even it is not a type ?


Solution

  • std::cout << nullptr; works in C++17. If it doesn't work for you, then either you're not using C++17 or your language implementation's support for C++17 is incomplete.

    Prior to C++17, std::cout << nullptr; didn't work because the overload std::ostream::operator<<(std::nullptr_t) didn't exist and there were no unambiguously best overload that nullptr could be implicitly converted to.

    Why it work with void* even it is not a type ?

    void* is a type and it works becase the overload std::ostream::operator<<(const void*); exists.