Why does reference_wrapper behave differently for built-in types?

I use std::reference_wrapperfor assembly type ( double) and for user-defined type ( std::string).

Why do they behave differently with the flow 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://coliru.stacked-crooked.com/a/fc4c614d6b7da690

Why in the first case, DR is converted to double and printed, and in the second - not? Is there any work around?


Ok, now I see that in the case of Ostream, I tried to call a template function that is not allowed:

#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://stackoverflow.com/a/34144470/225186
}
+4
source share
1 answer

TC . < basic_string templated, .

SR.get(), static_cast .

string_fun std::basic_string<C> . :

string_fun(SR);

SR , std::reference_wrapper<std::string>, , .

, :

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

};

Live Demo

, , string_fun - , , :

template<template<typename...> class C, typename T>
void
string_fun(C<T> const &t) {
  std::cout << 
    static_cast<std::conditional_t<
      std::is_same<
        std::reference_wrapper<T>, C<T>>::value, T, std::basic_string<T>>>(t) << std::endl;
}

Live Demo

+1

Source: https://habr.com/ru/post/1618955/


All Articles