Suppose that I have this template function:
template <typename T>
void foo(T &&t) {
std::forward<T>(t).foo();
std::forward<T>(t).bar();
std::forward<T>(t).baz();
}
Notice that I had to repeat std::forward multiple times for the same variable (to make sure that if T has ref-qualified foo()/bar()/baz(), the correct one will be called).
Is there a way to avoid repeating std::forward? It is not just redundant, but error-prone as well because I may forget to add std::forward somewhere.
Notice that I had to repeat std::forward multiple times for the same variable (to make sure that if T has ref-qualified foo()/bar()/baz(), the correct one will be called).
You should not repeat std::forward - you should only use it with the last call:
template <typename T>
void foo(T &&t) {
t.foo();
t.bar();
std::forward<T>(t).baz();
}
The way you wrote it, if the actual argument is rvalue, ref-qualified foo() may steal contents of t, and subsequent calls will not work as intended.
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