Indigo's Blog

An interesting case of function overloading in C++

Posted

Aka. Yet Another Reason Why C++ is a Broken Language

Consider the following code

#include <iostream>
void foo(int&&) {
    std::cout << "int\n";
}

void foo(float&&) {
    std::cout << "float\n";
}

int main() {
    int x = 1;
    float y = 1.0;
    foo(x);
    foo(y);
}

What do you expect this to print? If you think "int" followed by "float", then you'd be wrong. It actually prints them the other way around!

This is because int&& is an rvalue reference, meaning it binds to rvalues. x however is an lvalue. But there is hope! An implicit conversion exists from int to float, which produces an rvalue float! And so it does that conversion and calls the float&& overload. y does the same thing, and calls the int&& overload.

Gotta love C++