17
votes

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?

2

2 Answers

20
votes

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.

12
votes

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.