Is this std::ref behaviour logical?

前端 未结 3 1193
独厮守ぢ
独厮守ぢ 2021-02-04 23:29

Consider this code:

#include 
#include 

int xx = 7;

template
void f1(T arg)
{
    arg += xx;
}

template

        
3条回答
  •  天涯浪人
    2021-02-04 23:41

    A small modification to f2 provides the clue:

    template
    void f2(T arg)
    {
        arg.get() = xx;
    }
    

    This now does what you expect.

    This has happened because std::ref returns a std::reference_wrapper<> object. The assignment operator of which rebinds the wrapper. (see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator%3D)

    It does not make an assignment to the wrapped reference.

    In the f1 case, all is working as you expected because a std::reference_wrapper provides a conversion operator to T&, which will bind to the implicit right hand side of ints implicit operator+.

提交回复
热议问题