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!
Asked
Active
Viewed 62 times
0
-
From my tests, a temporary will never bind to the non-`const` version. And the non-temporary will always bind to the non- `const` version if they are not `const`. Look at [this](http://ideone.com/DF64I8) – Telokis Jun 15 '15 at 14:09
2 Answers
1
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

Barry
- 286,269
- 29
- 621
- 977
-
Thank you for the answer. I thought pass-by-reference-to-const only constraints the function from modifying the reference. But from the example, it also constraints on the caller?? It is great to know! – Sarah Jun 15 '15 at 14:37
0
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&)`

Some programmer dude
- 400,186
- 35
- 402
- 621