C++11 完美转发

简介在函数模板编程中,常有一种场景是把模板参数转发给另一个调用函数,这时候如果只提供值传递版本会显得效率太低。 引用折叠 与 模板推导。

在函数模板编程中,常有一种场景是把模板参数转发给另一个调用函数,这时候如果只提供值传递版本会显得效率太低。


引用折叠 与 模板推导。

本文转自:https://www.cnblogs.com/Braveliu/p/12235618.html

文章评论

    完美转发的应用示例

        2020-09-24    

    #include <iostream>
    using namespace std;
    
    void fun(int& x) { cout << "call lvalue ref" << endl; }
    void fun(int&& x) { cout << "call rvalue ref" << endl; }
    void fun(const int& x) { cout << "call const lvalue ref" << endl; }
    void fun(const int&& x) { cout << "call const rvalue ref" << endl; }
    
    template<typename T>
    void PerfectForward(T&& t)
    {
        std::cout << "T is a ref type?: " << std::is_reference<T>::value << std::endl;
        std::cout << "T is a lvalue ref type?: " << std::is_lvalue_reference<T>::value << std::endl;
        std::cout << "T is a rvalue ref type?: " << std::is_rvalue_reference<T>::value << std::endl;
    
        fun(forward<T>(t));
    }
    
    int main()
    {
        PerfectForward(10);           // call rvalue ref
    
        int a = 5;
        PerfectForward(a);            // call lvalue ref
        PerfectForward(move(a));      // call rvalue ref
    
        const int b = 8;
        PerfectForward(b);           // call const lvalue ref
        PerfectForward(move(b));     // call const rvalue ref
    
        system("pause");
        return 0;
    }
    
    /*
    T is a ref type?: 0
    T is a lvalue ref type?: 0
    T is a rvalue ref type?: 0
    call rvalue ref
    T is a ref type?: 1
    T is a lvalue ref type?: 1
    T is a rvalue ref type?: 0
    call lvalue ref
    T is a ref type?: 0
    T is a lvalue ref type?: 0
    T is a rvalue ref type?: 0
    call rvalue ref
    T is a ref type?: 1
    T is a lvalue ref type?: 1
    T is a rvalue ref type?: 0
    call const lvalue ref
    T is a ref type?: 0
    T is a lvalue ref type?: 0
    T is a rvalue ref type?: 0
    call const rvalue ref
    */
评论列表
完美转发的应用示例