overloading a function which differs from the original only by "const" in parameter list

78 Views Asked by At

I have a question about overloading a function with only difference in "const". For instance, if there is a function A, which is pass-by-reference, it is ok to overload it by pass-by-reference-to-const. However, when will the first one being invoked, and when will the second one being invoked? Thanks!

2

There are 2 best solutions below

1
On BEST ANSWER

It's definitely OK.

void foo(int& ) { std::cout << "ref\n"; }
void foo(const int& ) { std::cout << "cref\n"; }

The first one will be invoked if you pass a non-const lvalue of type int. The second one will be invoked in any other case.

int i = 4;
const int ci = i;

foo(4);  // cref
foo(i);  //  ref
foo(ci); // cref
foo(1L); // cref

struct X {
    operator int() { return 42; }
};

foo(X{}); // cref
0
On

I assume you mean something like

void A(int& arg)
{
    ...
}

void A(const int& arg)
{
    ...
}

Then you can use the function like

int i = 5;
A(i);  // will call `A(int&)`
A(5);  // will call `A(const int&)`

const int ci = 5;
A(ci);  // will call `A(const int&)`