Home > front end >  How to typecast class a to class b in c
How to typecast class a to class b in c

Time:11-26

Why ostringstream to ostream type casting working but vice versa not Working ?

int main()
{
   //part #1
   ostringstream   oss;
   ostream& os=oss ; 
   // ^^ It  works 
   
   //part #2
   ostream os2 ; 
   ostringstream& oss2=os2; 
    cout <<"address is "<<&oss; 
   // ^^ It doesn't  work 
    


     
    return 0;
}

Part #2 of code throws an error
" error: ‘std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits]’ is protected within this context" .
How can I fix this issue ?

Edit :- Take a look at this code , I want to access response in curlCall function without making anychange in any function's params


size_t CurlDataWrite(void* buf,size_t size,size_t nmemb,void* userp)
{
    
//code to write stream    
    ostream& os=*static_cast<ostream*>(userp);
    streamsize len=size*nmemb ; 
    if(os.write(static_cast<char*> (buf),len))
        return len ; 
        
        
        return 0 ;
}

void curlCall(ostream& os) 
{
 
   

  CURL* curl=curl_easy_init();  
 
 curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,&CurlDataWrite)  ; 
 curl_easy_setopt(curl,CURL_FILE,&os); 
 
 curl_easy_setopt(curl,CURLOPT_URL, "https://something.com"); 
 int code=curl_easy_perform(curl) ; 
 //how to get curl response here instead of in main function ???? 
}
int main()
{ 
    ostringstream oss;
    curlCall(oss);

    //i can get response here by calling the following code 
    cout << oss.str();
    return 0;
}

CodePudding user response:

how to get curl response here instead of in main function ????

void curlCall(ostream& os) is not designed for doing this. So you can do one of the following:

  • change curlCall interface so that it can do this (which means changing ostream parameter type to ostringstream)
  • don't do this in curlCall

If you want to do this in curlCall without changing curlCall interface, then you have self-contradictory requirements.

CodePudding user response:

Looking at your response to Jarod42's answer this seems to be more of a refactoring problem. Your problem is that you go from ostream -> ostringstream -> ostream, a possible solution is that you should just keep the function general and take in an ostream instead or separate the two functions.

  • Related