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
  • 23,276
  • 10
  • 49
  • 62
Jarvis
  • 63
  • 1
  • 11

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,809
  • 3
  • 46
  • 82
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
  • 223,364
  • 34
  • 402
  • 480
  • So what is with the down-vote? If there is something wrong with the answer I'll be happy to fix it. – juanchopanza Sep 24 '14 at 14:37
  • How is it that std::move(i) is taken as a rvalue?? – Jarvis Sep 24 '14 at 15:23
  • @user3258312 It is a clever combination of casting to rvalue reference `&&` and hiding the name. See [this related SO post](http://stackoverflow.com/questions/7510182/how-does-stdmove-transfer-values-into-rvalues). – juanchopanza Sep 24 '14 at 15:28