函数转发参数,什么都不做

Function forwarding argument and simply doing nothing

对于模板默认情况,我需要一个函数,它什么都不做,只是简单地转发它作为参数接收的任何内容。具体来说,应该保留引用、const-ness 等。写作 transparent(/* something */) 应该完全等同于写作 /* something */.

以下函数定义是否正确以实现该目的?

template <class S>
decltype(auto) transparent (S && s) { return std::forward<S> (s); }

您的实施很好,但需要注意以下几点:

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

但是你为什么需要这个?一个常见的用途 std::forward 模板中的 warpper 是这样的:

template<class T>
void wrapper(T&& arg) 
{
    foo(std::forward<T>(arg)); // Forward a single argument.
}

加一个 constexpr 就可以了。 prvalues 将产生 xvalues;但是,这并不能改进,因为无法使用重载决策来区分纯右值和虚值。

您将无法将 0 作为空指针常量或字符串文字作为初始值设定项进行正确转发,但实现此目的的唯一方法是使用宏(这不是您想要的)对于).