Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Overloading Based on Value vs. Const Reference

Does declaring something like the following

void foo(int x)        { std::cout << "foo(int)"         << std::endl; } void foo(const int &x) { std::cout << "foo(const int &)" << std::endl; } 

ever make sense? How would the caller be able to differentiate between them? I've tried

foo(9);  // Compiler complains ambiguous call.  int x = 9; foo(x);  // Also ambiguous.  const int &y = x; foo(y);  // Also ambiguous. 
like image 540
kirakun Avatar asked Mar 28 '11 21:03

kirakun


People also ask

Can const function be overloaded?

C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer.

Can const function be overloaded in C++?

C++ allows functions to be overloaded on the basis of the const-ness of parameters only if the const parameter is a reference or a pointer.

Why do we use const in operator overloading?

It tells other people that use your class that you will not be changing the other value when you say something like: myObject = other; and it enforces this so you can't accidentally change other .

What are the different types of function overloading?

There are mainly two types of overloading, i.e. function overloading and operator overloading. Function overloading improves the code readability, thus keeping the same name for the same action.


1 Answers

The intent seems to be to differenciate between invocations with temporaries (i.e. 9) and 'regular' argument passing. The first case may allow the function implementation to employ optimizations since it is clear that the arguments will be disposed afterwards (which is absolutely senseless for integer literals, but may make sense for user-defined objects).

However, the current C++ language standard does not offer a way to overload specifically for the 'l/r-valueness' of arguments - any l-value being passed as argument to a function can be implicitly converted to a reference, so the ambiguity is unavoidable.

C++11 introduces a new tool for a similar purpose — using r-value references, you can overload as follows

void foo(int x)        { ... } void foo(const int &&x) { ... } 

... and foo(4) (a temporary, r-value passed as argument) would cause the compiler to pick the second overload while int i = 2; foo(i) would pick the first.

(note: even with the new toolchain, it is not possible to differentiate between the cases 2 and 3 in your sample!)

like image 126
Alexander Gessler Avatar answered Sep 30 '22 16:09

Alexander Gessler