operator<<(os, 42) vs os << 42

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std; // for this experiment

int main() {
    operator<<(cout, 42);
    // ambiguous overload error; candidates offer char,
    // signed char, and unsigned char for the second
    // parameter.
    // Apparently you can only pass a char, a c-string
    // or a std::string for the second parameter.
    // But then why can you do this?
    cout << 42;
}

This StackOverflow post should answer your question precisely: https://stackoverflow.com/questions/45981648/operatorstdostream-int-is-ambiguous

operator<<(std::cout, 42); is not equivalent to std::cout << 42;, it's equivalent to std::cout.operator<<(42);
Line 5 uses Argument-Dependent Lookup (ADL), which finds multiple, ambiguous candidates.

(Note: All credit to Sombrero Chicken and Remy Lebeau, I had no idea why that happened before reading it.)
Last edited on
The << operators for outputting integers are defined as member functions so you have to write cout.operator<<(42);
https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
Topic archived. No new replies allowed.