vendredi 22 mai 2015

Why specifying a lvalue reference for *this on a member function is different from not specifying anything?

Consider this code:

#include <iostream>
using namespace std;

struct A {
    void f() { cout << "A::f" << endl; }
    void f() const { cout << "A::f const" << endl; }
};

struct B {
    void f() & { cout << "B::f &" << endl; }
    void f() const & { cout << "B::f const &" << endl; }
};

A getA() { return A{}; }
B getB() { return B{}; }

int main() {
    getA().f();
    getB().f();
}

which prints

A::f
B::f const &

For B, the const overload gets selected, not the non-const one. I guess this means that specifying a lvalue ref qualifier for *this is different from not specifying anything at all. Why is that? Does the "implicit this argument" change type and the const overload now becomes a better candidate in overload resolution?

Aucun commentaire:

Enregistrer un commentaire