Why rvalue reference pass as lvalue reference?

后端 未结 2 1315
爱一瞬间的悲伤
爱一瞬间的悲伤 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 <typename T>
    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 <typename T>
    void pass(T&& v) {
        reference(std::forward<T>(v));
    }
    

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

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

    See this;

    0 讨论(0)
  • 2020-12-18 04:59

    Why the template function pass v to reference() as lvalue?

    That's because v is an lvalue. Wait, what? v is an rvalue reference. The important thing is that it is a reference, and thus an lvalue. It doesn't matter that it only binds to rvalues.

    If you want to keep the value category, you will have to do perfect forwarding. Perfect forwarding means that if you pass an rvalue (like in your case), the function will be called with an rvalue (instead of an lvalue):

    template <typename T>
    void pass(T&& v) {
        reference(std::forward<T>(v)); //forward 'v' to 'reference'
    }
    
    0 讨论(0)
提交回复
热议问题