What are the main purposes of using std::forward and which problems it solves?

后端 未结 6 2051
执念已碎
执念已碎 2020-11-21 07:12

In perfect forwarding, std::forward is used to convert the named rvalue references t1 and t2 to unnamed rvalue references. What is the

6条回答
  •  既然无缘
    2020-11-21 07:48

    A point that hasn't been made crystal clear is that static_cast handles const T& properly too.
    Program:

    #include 
    
    using namespace std;
    
    void g(const int&)
    {
        cout << "const int&\n";
    }
    
    void g(int&)
    {
        cout << "int&\n";
    }
    
    void g(int&&)
    {
        cout << "int&&\n";
    }
    
    template 
    void f(T&& a)
    {
        g(static_cast(a));
    }
    
    int main()
    {
        cout << "f(1)\n";
        f(1);
        int a = 2;
        cout << "f(a)\n";
        f(a);
        const int b = 3;
        cout << "f(const b)\n";
        f(b);
        cout << "f(a * b)\n";
        f(a * b);
    }
    

    Produces:

    f(1)
    int&&
    f(a)
    int&
    f(const b)
    const int&
    f(a * b)
    int&&
    

    Note that 'f' has to be a template function. If it's just defined as 'void f(int&& a)' this doesn't work.

提交回复
热议问题