[C++11]forward完美转发

[C++11]forward完美转发_第1张图片

// 函数原型
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<T>(t);

推导规则:

[C++11]forward完美转发_第2张图片

#include 
using namespace std;

template<typename T>
void printValue(T& t)
{
    cout << "l-value: " << t << endl;
}

template<typename T>
void printValue(T&& t)
{
    cout << "r-value: " << t << endl;
}

template<typename T>
void testForward(T && v)
{
    printValue(v);
    printValue(move(v));
    printValue(forward<T>(v));
    cout << endl;
}

int main()
{
    testForward(520);
    int num = 1314;
    testForward(num);
    testForward(forward<int>(num));
    testForward(forward<int&>(num));
    testForward(forward<int&&>(num));

    return 0;
}



/*作者: 苏丙榅
链接: https://subingwen.cn/cpp/move-forward/#2-forward
来源: 爱编程的大丙*/

测试结果:

[C++11]forward完美转发_第3张图片

该文参考于下面链接
链接: https://subingwen.cn/cpp/move-forward/#2-forward

你可能感兴趣的:([C++11],算法,c++,C++11,forward,move)