lundi 7 décembre 2015

Why reference_wrapper behaves differently for built-in types?

I have the following use of std::reference_wrapper for a build in type (double) and for a user defined type (std::string).

Why do they behave differently in the case of the stream operator?

#include<functional> //reference wrapper
#include<iostream>

void fd(double& d){}
void fs(std::string& s){}

int main(){

   double D = 5.;
   std::reference_wrapper<double> DR(D);
   std::cout << "DR = " << DR << std::endl; //ok 
   fd(DR); // ok

   std::string S = "hello";
   std::reference_wrapper<std::string> SR(S);
   std::cout << "SR = " << static_cast<std::string&>(SR) << std::endl; // ok
   std::cout << "SR = " << SR << std::endl; // error: invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'std::reference_wrapper<std::string>')
   fs(SR); // ok 
}

http://ift.tt/1NGKUot

Why in the first case DR is converted to double and printed and in the second it is not? Is there a work around?


Ok, I see now, in the ostream case I was trying to called a templated function that is not resolved:

#include<functional> //reference wrapper

void double_fun(double const& t){};

template<class C>
void string_fun(std::basic_string<C> const& t){};


int main(){

   double D = 5.;
   std::reference_wrapper<double> DR(D);
   double_fun(DR); //ok

   std::string S = "hello";
   std::reference_wrapper<std::string> SR(S);
   string_fun(SR); // error: no matching function for call to 'string_fun'
   string_fun(SR.get()); // ok
   string_fun(static_cast<std::string&>(SR)); // ok
   string_fun(*&SR); // would be ok if `std::reference_wrapper` was designed/coded differently, see http://ift.tt/1XQvmcJ
}

Aucun commentaire:

Enregistrer un commentaire