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()
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:
i (then considered as a rvalue)g(int{i})std::move(); then the original i must not be used afterwards.g(std::move(i))R-value references is defined since c++ 11, You should change your compiler version to c++ 11.
Please check out this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With