0

If there's one method that takes pointer as a parameter, and another overloaded method that takes a reference as a parameter, how do I call one or the other specifically?

For example.

int foo (int const& lippman) { \do something }
int foo (int && lippman) { \do something else }

-- So now when I want to call one or the other, how do I call it/how does the compiler distinguish the two(obviously by parameter, but how?)

Thanks

taocp
  • 22,732
  • 9
  • 48
  • 60
Jarvis
  • 63
  • 1
  • 10

2 Answers2

3
int foo (X const&);
int foo (X&&);

These are not by pointer. The first is by const reference, the second is by r-value reference. To distinguish between them:

X x{};
foo( x ); // call the first version
foo( std::move(x) ); // call the second version (also with temporary: foo( X{} ); )

Note: A third overload (by pointer) would be:

int foo(X* x); // or "const X* x" or "const X* const x"

To call with the same x instance as above:

foo(&x); // get address of x and pass to "foo"
utnapistim
  • 26,020
  • 3
  • 44
  • 78
2

Both functions have references as parameters, the first an lvalue reference, the second an rvalue reference.

The first one overload will be called with lvalues, the second with rvalues:

int i = 42;
foo(i);  // first one gets called
foo(42); // second one gets called

This behaviour is set out in the C++ standard, and compilers need to be able to figure out what is an lvalue and what is an rvalue, to pick the correct overload.

Note that you can use std::move to make an lvalue look like an rvalue:

foo(std::move(i)); // second overload gets called

See a working example.

juanchopanza
  • 216,937
  • 30
  • 383
  • 461