Consider the two following:
template <class Function>
void apply(Function&& function)
{
std::forward<Function>(function)();
}
and
template <class Function>
void apply(Function&& function)
{
function();
}
In what case is there a difference, and what concrete difference is it ?
There is a difference if Function
's operator()
has ref qualifiers. With std::forward
, the value category of the argument is propagated, without it, the value category is lost, and the function will always be called as an l-value. Live Example.
#include <iostream>
struct Fun {
void operator()() & {
std::cout << "L-Value\n";
}
void operator()() && {
std::cout << "R-Value\n";
}
};
template <class Function>
void apply(Function&& function) {
function();
}
template <class Function>
void apply_forward(Function&& function) {
std::forward<Function>(function)();
}
int main () {
apply(Fun{}); // Prints "L-Value\n"
apply_forward(Fun{}); // Prints "R-Value\n"
}
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