Hello I have this example from C++ primer:
template <typename T> void f(T&& x) // binds to nonconstant rvalues { std::cout << "f(T&&)\n"; } template <typename T> void f(T const& x) // lvalues and constant revalues { std::cout << "f(T const&)\n"; }
And here is my attempt to test the output:
int main(){
int i = 5;
int const ci = 10;
f(i); // f(T& &&) -> f(int&)
f(ci); // f(T const&) -> f(int const&)
f(5); // f(T &&) -> f(int&&)
f(std::move(ci)); // f(T&&) -> f(int const&&)
cout << '\n';
}
The output:
f(T&&)
f(T const&)
f(T&&)
f(T&&)
In the book the version of
f
taking a forwarding reference is said to bind only to non-constant rvalues but inmain
I've passed a constant rvaluef(5)
andf(std::move(ci))
but still the first version called.Is there a way to call the second version
f(T const&)
passing an rvalue? I know I can do it explicitly:f<int const&>(5);
orf<int const&>( std::move(ci) );
but I want to know where can be called passing in an rvalue? Thank you!I think the comment after the forwarding reference version of
f
is not correct:f(T&&) // binds to nonconstant rvalues
because it can be bound to constant rvalues so for example:f(std::move(ci)); // f(int const&&) and not f(int const&)