Why does a perfect forwarding function have to be templated?

后端 未结 1 922
予麋鹿
予麋鹿 2021-01-01 16:31

Why is the following code valid:

template
void foo(T1 &&arg) { bar(std::forward(arg)); }

std::string str = \"Hello Worl         


        
相关标签:
1条回答
  • 2021-01-01 16:47

    First of all, read this to get a full idea of forwarding. (Yes, I'm delegating most of this answer elsewhere.)

    To summarize, forwarding means that lvalues stay lvalues and rvalues stay rvalues. You can't do that with a single type, so you need two. So for each forwarded argument, you need two versions for that argument, which requires 2N combinations total for the function. You could code all the combinations of the function, but if you use templates then those various combinations are generated for you as needed.


    If you're trying to optimize copies and moves, such as in:

    struct foo
    {
        foo(const T& pX, const U& pY, const V& pZ) :
        x(pX),
        y(pY),
        z(pZ)
        {}
    
        foo(T&& pX, const U& pY, const V& pZ) :
        x(std::move(pX)),
        y(pY),
        z(pZ)
        {}
    
        // etc.? :(
    
        T x;
        U y;
        V z;
    };
    

    Then you should stop and do it this way:

    struct foo
    {
        // these are either copy-constructed or move-constructed,
        // but after that they're all yours to move to wherever
        // (that is, either: copy->move, or move->move)
        foo(T pX, U pY, V pZ) :
        x(std::move(pX)),
        y(std::move(pY)),
        z(std::move(pZ))
        {}
    
        T x;
        U y;
        V z;
    };
    

    You only need one constructor. Guideline: if you need your own copy of the data, make that copy in the parameter list; this enables the decision to copy or move up to the caller and compiler.

    0 讨论(0)
提交回复
热议问题