Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating std::forward for the same variable

Tags:

c++

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.

like image 832
geza Avatar asked Sep 12 '26 20:09

geza


1 Answers

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.

like image 101
Eugene Avatar answered Sep 14 '26 09:09

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!