Following is the code brought from this question.
// [I]
void overloaded_function(const std::string& param) {
std::cout << "const std::string& version: " << param << '\n';
}
// [II]
void overloaded_function(std::string&& param) {
std::cout << "std::string&& version: " << param << '\n';
}
template <typename T>
void pass_through_f(T&& param) {
overloaded_function(std::forward<T>(param));
}
template <typename T>
void pass_through(T&& param) {
overloaded_function(param);
}
int main() {
std::string str = "Hello World";
pass_through_f(str); // (1)
pass_through_f(std::move(str)); // (2)
std::cout << "----------\n";
pass_through(str); // (3)
pass_through(std::move(str)); // (4)
return 0;
}
const std::string& version: Hello World
std::string&& version: Hello World
----------
const std::string& version: Hello World
const std::string& version: Hello World
When I use pass_through_f()
, the result between (1)
and (2)
is different but they are same when pass_though()
is called.
My question is, how is the result of (4)
same with (3)
? Here's type inferencing process that I thought:
In
(4)
, return value of some function is r-value, soT
ofpass_through()
is inferred as a type same with passed argument. ThusT
isstd::string&&
.std::string&&
is r-value reference, and r-value reference is r-value so it callsoverloaded_function() [II]
. Thus its result is same with whenstd::forward
is used.
But result is different with my thought. I think I'm misunderstanding something about the way std::forward
works.