std :: forward的实现 [英] The implementation of std::forward
问题描述
我正在阅读新C ++概述(C ++ 11/14)(仅PDF) ,在幻灯片288上提供了 std :: forward
:
I'm reading Overview of the New C++ (C++11/14) (PDF only), at Slide 288 it gives an implementation of std::forward
:
template<typename T> // For lvalues (T is T&),
T&& std::forward(T&& param) // take/return lvalue refs.
{ // For rvalues (T is T),
return static_cast<T&&>(param); // take/return rvalue refs.
}
然后在文本中给出另一个实现:
And then gives another implemention in text:
通常的
std :: forward
实现是:
template<typename T>
struct identity {
typedef T type;
};
template<typename T>
T&& forward(typename identity<T>::type&& param)
{
return static_cast<identity<T>::type&&>(param);
}
有什么区别?为什么后者是通常的实现?
What is the difference? Why is latter the usual implementation?
推荐答案
第一个问题是您可以编写 std: :forward(x)
,它不会做您想要的事情,因为它总是产生左值引用。
The problem with the first is that you can write std::forward(x)
, which doesn't do what you want, since it always produces lvalue references.
第二种情况下的参数是非推导上下文,防止自动推导模板参数。这迫使您编写 std :: forward< T(x)
,这是正确的选择。
The argument in the second case is a non-deduced context, preventing automatic deduction of the template argument. This forces you to write std::forward<T>(x)
, which is the right thing to do.
此外,第二次重载的参数类型应为 typename identity< T> :: type&
,因为习惯用法是 std的输入: :forward
始终是左值。
Also, the argument type for the second overload should be typename identity<T>::type&
because the input to idiomatic use of std::forward
is always an lvalue.
编辑:该标准实际上要求的签名与此等效( ,顺便说一句,正是libc ++所具有的):
The standard actually mandates a signature equivalent to this one (which, incidentally, is exactly what libc++ has):
template <class T> T&& forward(typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward(typename remove_reference<T>::type&& t) noexcept;
这篇关于std :: forward的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!