Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express constness of a forwarding reference?

Tags:

c++

c++11

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) { ... }
like image 535
Ton van den Heuvel Avatar asked Jul 14 '16 09:07

Ton van den Heuvel


1 Answers

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) { ... }
like image 197
Jonathan Wakely Avatar answered Nov 11 '22 12:11

Jonathan Wakely