【发布时间】:2020-10-03 15:03:28
【问题描述】:
您如何理解“std::forward 只是语法糖”?真的吗?如果您能详细解释下面的相关代码,我将不胜感激。
根据文档(https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a00416_source.html),
这里是std::forward的实现:
/**
* @brief Forward an lvalue.
* @return The parameter cast to the specified type.
*
* This function is used to implement "perfect forwarding".
*/
template<typename _Tp>
constexpr _Tp&&
forward(typename std::remove_reference<_Tp>::type& __t) noexcept
{ return static_cast<_Tp&&>(__t); }
/**
* @brief Forward an rvalue.
* @return The parameter cast to the specified type.
*
* This function is used to implement "perfect forwarding".
*/
template<typename _Tp>
constexpr _Tp&&
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
{
static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
" substituting _Tp is an lvalue reference type");
return static_cast<_Tp&&>(__t);
}
/**
* @brief Convert a value to an rvalue.
* @param __t A thing of arbitrary type.
* @return The parameter cast to an rvalue-reference to allow moving it.
*/
template<typename _Tp>
constexpr typename std::remove_reference<_Tp>::type&&
move(_Tp&& __t) noexcept
{ return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
【问题讨论】:
-
阅读 scott meyers “有效的现代 c++” - 深入了解移动和前进,它们只是演员表
-
“语法糖”是指一种语言特性,它不添加功能,而只是为了使代码更易于阅读和理解。 (这可能是 Mary Poppins 的参考,即“一勺糖使药物下降”)
-
如您所见,
std::forward是一个简单的静态转换。 -
你对“syntactic sugar”这个词的理解是什么?
-
@ThomasSablik 很高兴再次见到您!这是真的吗?我完全理解这是昨天在您的帮助下进行的类型转换。我确实见过很多这样的说法。
标签: c++ c++11 c++14 perfect-forwarding syntactic-sugar