Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass lvalue to function taking rvalue only without templates

My question is simple

#include <iostream>

using namespace std;

template <typename T>
void f(T&& i) {
        cout << i << endl;
}

void g(int&& i) {
        cout << i << endl;
}

int main() {
        int i = 0;
        f(i); // works fine
        g(i); // candidate function not viable: no known conversion from 'int' to 'int &&'
              // for 1st argument void g(int&& i)

}

Why can I pass an lvalue to templated function f() but not non templated function g()

like image 455
Ankit Rohilla Avatar asked Oct 25 '25 00:10

Ankit Rohilla


2 Answers

Your f() function does not expect a rvalue but a forwarding reference.
Despite the fact that f() and g() look very similar (due to the && symbol), they are very different.
(see for example Is there a difference between universal references and forwarding references?)

If you really want to pass i to g(), you have two options:

  • provide a temporary object which is a copy of i (then considered as a rvalue)
    g(int{i})
  • force the conversion to rvalue reference with std::move(); then the original i must not be used afterwards.
    g(std::move(i))
    (https://en.cppreference.com/w/cpp/utility/move)
like image 128
prog-fh Avatar answered Oct 27 '25 13:10

prog-fh


R-value references is defined since c++ 11, You should change your compiler version to c++ 11.

Please check out this link



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!