I am trying to understand std::reference_wrapper
.
The following code shows that the reference wrapper does not behave exactly like a reference.
#include <iostream>
#include <vector>
#include <functional>
int main()
{
std::vector<int> numbers = {1, 3, 0, -8, 5, 3, 1};
auto referenceWrapper = std::ref(numbers);
std::vector<int>& reference = numbers;
std::cout << reference[3] << std::endl;
std::cout << referenceWrapper.get()[3] << std::endl;
// I need to use get ^
// otherwise does not compile.
return 0;
}
If I understand it correctly, the implicit conversion does not apply to calling member functions. Is this an inherent limitation? Do I need to use the std::reference_wrapper::get
so often?
Another case is this:
#include <iostream>
#include <functional>
int main()
{
int a = 3;
int b = 4;
auto refa = std::ref(a);
auto refb = std::ref(b);
if (refa < refb)
std::cout << "success" << std::endl;
return 0;
}
This works fine, but when I add this above the main
definition:
template <typename T>
bool operator < (T left, T right)
{
return left.someMember();
}
The compiler tries to instantiate the template and forgets about implicit conversion and the built in operator.
Is this behavior inherent or am I misunderstanding something crucial about the std::reference_wrapper
?
std::reference_wrapper
has some very specific uses for library-authors, being relevant to perfect forwarding and storing arguments (see e.g.std::bind
andstd::thread
). I don't recommend using it outside of those situations. – Xeo Aug 8 '13 at 13:38reference_wrapper
is not a replacement for references. – R. Martinho Fernandes Aug 8 '13 at 13:39template <typename T> bool operator < (T left, T right) { return left.someMember(); }
is an example of what to NEVER EVER EVER EVER DO when overloading an operator. Any problems that result due to that code are not the problem of anything else in your code base. (ok, maybe in some ridiculously restricted and controllednamespace
to be found via ADL, or similar other contrived situations) – Yakk - Adam Nevraumont Aug 8 '13 at 14:03