0

Please refer to the below simple scenario:

void test(int k){
 cout<<"Passed as value"<<endl;
 cout<<k<<endl;
}

void test(int &k){
 cout<<"Passed as reference"<<endl;
  cout<<k<<endl;
}

int main(){
 int x = 10;
 test(x);
}

As far as my understanding is concerned, when you call a function, at that time the compiler has no way of knowing if the variable passed to it is by value or by reference. Thus, I understand why the compiler gives the error that call of overloaded ‘test(int&)’ is ambiguous. Is there any way that we can specify while calling the function itself that I intend to pass the value as reference?" N.B. I already know the work around this issue by passing the variable as address.

  • See [Overload resolution between object, rvalue reference, const reference](https://stackoverflow.com/a/17961890/12002570) – Jason Nov 27 '22 at 10:25
  • If by "passing the variable as address" you mean using the pointer-to operator `&` as in `&x` then that won't call any of the functions. The type of `&x` is `int*`, which is distinct from both `int` and `int&`. – Some programmer dude Nov 27 '22 at 10:26
  • See more exact duplicate: [Ambiguous Reference/Value Versions of Functions](https://stackoverflow.com/a/5857326/12002570) – Jason Nov 27 '22 at 10:27
  • The compiler knows the value type passed; It's just that both overloads here have the exact same precedence and the compiler has no rules to choose one over the other. If the compiler wouldn't consider `x` is an lvalue, why would it condiser the second overload to be applicable? In this case you should change the overloads to `void test(int& k);` and `void test(int const& k)` to remove the ambiguity. – fabian Nov 27 '22 at 10:27

0 Answers0