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); }
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).
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.
}
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