-2

The first lines of code will return 112 but why? 1 is not supposed to be of type int&&? And why it is working in the second example of code i.e. returning 312?

void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(t); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}
void fun(int&) { cout << 1; }
void fun(int const&) { cout << 2; }
void fun(int&&) { cout << 3; }

template
<typename T>
void fun2(T&& t) { fun(std::forward<T>(t)); }

int main() {
  int x{};
  int const y{};
  fun2(1);
  fun2(x);
  fun2(y);
}
Sneftel
  • 40,271
  • 12
  • 71
  • 104
Gauvain
  • 75
  • 4

1 Answers1

0

std::forward basically means that you want to preserve the lvalueness or rvalueness of the calling argument when passing/forwarding it to another function.

So in the second example you keep the rvalueness, while in the first example you pass t as a lvalue reference.

You might want to read a bit more on universal/forwarding reference for example here: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

maxbachmann
  • 2,862
  • 1
  • 11
  • 35