Please consider the following template function interface with a forwarding reference argument:
template<typename T>
void f(T&& t) { ... }
In this case, f
either takes an lvalue reference, or an rvalue reference, depending on the type of the argument for f
. How can I express that f
does not modify its parameter? The following naive approach does not work, since it no longer allows passing lvalue references to f
:
template<typename T>
void f(const T&& t) { ... }
How can I express that f does not modify its parameter?
If the function doesn't modify its parameter then there is no benefit to using a forwarding reference. You use a forwarding reference when you want to forward the parameter on to some other function which cares whether the argument is an lvalue or an rvalue (because maybe there are separate overloads for lvalues and rvalues, and the rvalue one can be more efficient).
If your function doesn't modify the argument then it shouldn't need to care whether it has an lvalue or rvalue, so it can just take const T&
unconditionally. That can bind to both lvalues and rvalues, and promises not to modify the parameter.
template<typename T>
void f(const T& t) { ... }
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