Why rvalue reference pass as lvalue reference?

后端 未结 2 1322
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 04:33

pass() reference argument and pass it to reference, however a rvalue argument actually called the reference(int&) instead of

2条回答
  •  没有蜡笔的小新
    2020-12-18 04:42

    template 
    void pass(T&& v) {
        reference(v);
    }
    

    You are using a Forwarding reference here quite alright, but the fact that there is now a name v, it's considered an lvalue to an rvalue reference.

    Simply put, anything that has a name is an lvalue. This is why Perfect Forwarding is needed, to get full semantics, use std::forward

    template 
    void pass(T&& v) {
        reference(std::forward(v));
    }
    

    What std::forward does is simply to do something like this

    template 
    void pass(T&& v) {
        reference(static_cast(v));
    }
    

    See this;

提交回复
热议问题