1

A template rvalue reference acts differently than a normal rvalue reference.

void foo1 (int&& i) {}
template<typename T> void foo2 (T&& i) {}

int main ()
{
  int i = 3;
  foo1(i);  // ERROR as expected
  foo2(i);  // OK, but why?
}

Normal rvalue is giving error as expected, but template rvalue silently doesn't give error.
In fact there is a post on how to solve the issue in case of templates: How to make template rvalue reference parameter ONLY bind to rvalue reference?

Why are they different and is there any relevant section in the standard?

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 2
    _Short answer:_ It is so-called forwarding reference, which has special template argument deduction rules. These allow generating different instances for both lvaule and rvalue function arguments of the same type. In practice, forwarding references are mostly used for perfect forwarding (typically, in a combination with a template pack). – Daniel Langr Aug 09 '21 at 05:54

0 Answers0