c++ - How to correctly use std::reference_wrappers -


i trying understand std::reference_wrapper.

the following code shows reference wrapper not behave 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;                // need use ^               // otherwise not compile.     return 0; } 

if understand correctly, implicit conversion not apply calling member functions. inherent limitation? need use std::reference_wrapper::get often?

another case this:

#include <iostream> #include <functional>  int main() {     int = 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, when add above main definition:

template <typename t> bool operator < (t left, t right) {     return left.somemember(); } 

the compiler tries instantiate template , forgets implicit conversion , built in operator.

is behavior inherent or misunderstanding crucial std::reference_wrapper?

class std::reference_wrapper<t> implements explicit converting operator t&:

operator t& () const noexcept; 

and more explicit getter:

t& get() const noexcept; 

the implicit operator called when t (or t&) required. instance

void f(some_type x); // ... std::reference_wrapper<some_type> x; some_type y = x; // implicit operator called f(x);            // implicit operator called , result goes f. 

however, t not expected and, in case, must use get. happens, mostly, in automatic type deduction contexts. instance,

template <typename u> g(u x); // ... std::reference_wrapper<some_type> x; auto y = x; // type of y std::reference_wrapper<some_type> g(x);       // u = std::reference_wrapper<some_type> 

to some_type instead of std::reference_wrapper<some_type> above should do

auto y = x.get(); // type of y some_type g(x.get());       // u = some_type 

alternativelly last line above replaced g<some_type>(x);. however, templatized operators (e.g. ostream::operator <<()) believe can't explicit type.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -