I am trying to understand how std::ref works.
#include <functional>
#include <iostream>
template <class C>
void func(C c){
    c += 1;
}
int main(){
    int x{3};
    std::cout << x << std::endl;
    func(x);
    std::cout << x << std::endl;
    func(std::ref(x));
    std::cout << x << std::endl;
}
Output : 3 3 4
In the code above, I think the template parameter C for the third function call is instantiated as std::reference_wrapper<int>.
While reading the reference,
I noticed there is no += operator in std::reference_wrapper<int>.
Then, how is c += 1; valid?
std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.
A reference_wrapper<Ty> is a copy constructible and copy assignable wrapper around a reference to an object or a function of type Ty , and holds a pointer that points to an object of that type. A reference_wrapper can be used to store references in standard containers, and to pass objects by reference to std::bind .
No, you cannot do this reliably in C++03, because the constructor of pair takes references to T , and creating a reference to a reference is not legal in C++03.
how is
c += 1;valid?
Because reference_wrapper<int> is implicitly convertible to int& via its conversion operator; and implicit conversions are considered for operands if there is no suitable overload for the operand type itself.
std::reference_wrapper<T> has a conversion operator to T&. This means that std::reference_wrapper can be implicitly converted to int& in your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With