delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2004/03/11/06:15:48

X-Authentication-Warning: delorie.com: mail set sender to djgpp-bounces using -f
From: "Anthony" <akantsel AT integra DOT rmt DOT ru>
Newsgroups: comp.os.msdos.djgpp
Subject: Why does this code fails?
Date: Thu, 11 Mar 2004 14:11:07 +0300
Organization: Radio-MSU NOC, Moscow State University
Lines: 50
Message-ID: <c2phh0$17jb$1@alpha2.radio-msu.net>
NNTP-Posting-Host: integra.rmt.ru
X-Trace: alpha2.radio-msu.net 1079003488 40555 81.13.30.150 (11 Mar 2004 11:11:28 GMT)
X-Complaints-To: usenet AT radio-msu DOT net
NNTP-Posting-Date: Thu, 11 Mar 2004 11:11:28 +0000 (UTC)
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2600.0000
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

#include <iostream>
#include <stdexcept>
#include <fstream>

class mystream {
 private:
 std::ostream *pstream;
 public:
 mystream(std::ostream& s) : pstream(&s) {}
 mystream() : pstream(NULL) {}

 operator std::ostream&() throw(std::runtime_error)
 {
  if(pstream) {
   return *pstream;
  } else {
   throw std::runtime_error("Convertion of NULL stream.");
  }
 }
void assign(std::ostream& s);
...
};

mystream mstr;

int main()
{
 mstr.assign(std::cout);
 try{
  static_cast<std::ostream&>(mstr) << "Hello world";    // This compiles
fine
  mstr << "Hello world";                                                //
This gives error 'no match for operator<< 'in mstr << "Hello world"'
 }
 catch(std::runtime_error& err) {
  std::cerr << "\n ERROR: " << err.what();
 }
 std::cin.get();
 return 0;
}
-------------------------------------
Why doesn't convertion by default work? How to make it work with no
cast-ing?
The goal is to have a global static reference to a stream, where some code
can do output and another code can change this output destanation, like make
it go to cout, then after sometime to a file stream, etc. Is there better
way to do this than this code?
Thanks.


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019