Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function forwarding argument and simply doing nothing

For a template default case, I need a function that does nothing but simply forwards whatever it receives as an argument. Specifically, references, const-ness etc. should be preserved. Writing transparent(/* something */) should be completely equivalent to writing /* something */.

Is the following function definition correct for achieving that purpose?

template <class S>
decltype(auto) transparent (S && s) { return std::forward<S> (s); }
like image 915
JohnB Avatar asked Dec 25 '15 09:12

JohnB


2 Answers

Add a constexpr and it's as good as it gets. prvalues will yield xvalues; However, that's not improvable since one cannot distinguish prvalues and xvalues using overload resolution.

You won't be able to properly forward 0 as a null pointer constant or string literals as initializers, but the only way to achieve that would be a macro (which is not what you're going for).

like image 141
Columbo Avatar answered Nov 05 '22 12:11

Columbo


Your implementation is fine, but here are some things to come to mind:

If a call to transparent () passes an rvalue std::string, then is deduced to std::string, and std::forward ensures that an rvalue reference is return.

If a call to transparent () passes a const lvalue std::string, then S is deduced to const std::string&, and std::forward ensures that a const lvalue reference will return

If a call to transparent () passes a non-const lvalue std::string, then S is deduced to std::string&, and std::forward ensures that a non-const lvalue reference will return

But why do you need this? A common use to std::forward in templates is to the a warpper like that:

template<class T>
void wrapper(T&& arg) 
{
    foo(std::forward<T>(arg)); // Forward a single argument.
}
like image 37
Benny Isaacs Avatar answered Nov 05 '22 13:11

Benny Isaacs