c++11:为什么 std::forward 中的 static_assert 是必需的?

标签 c++ c++11 rvalue-reference

在 move.h 中,forward 有两个重载

template<typename _Tp>
constexpr _Tp&&
forward(typename std::remove_reference<_Tp>::type& __t) noexcept
{
    return static_cast<_Tp&&>(__t);
}

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

我看到 static_assert 是为了防止意外地将右值转换为左值。右值版本可以这样实现吗:

template<typename _Tp>
typename std::remove_reference<_Tp>::type&&         
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
{
    return __t;
}

最佳答案

关于为什么将右值作为左值转发是危险的示例,请参见 N2951 的用例 C .这个用例展示了这样做如何使创建悬挂引用变得容易。

关于c++11:为什么 std::forward 中的 static_assert 是必需的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335916/

相关文章:

c++ - 使用 cmake 构建 tensorflow 服务客户端

c++ - 该 vector 的大小为 2,但它在索引 100 中仍有一个值

c++ - 有错误的程序还能编译吗?

c++ - 模板化函数只接受右值

c++ - 如何对可变参数函数中的所有参数调用 std::forward ?

c++ - 是否可以将 std::move 对象移出函数? (C++11)

c++ - 使用 For 循环对队列进行入队和出队 - C++

c++ - 无法访问 IplImage 数据

C++ 为什么在定义重载和引用函数时每个函数都应该有一个引用限定符

c++ - 直接初始化与值初始化