Hi!
I've tried to find an answer to this in the FAQ and elsewhere on the
net, without success. I'm fairly sure that the issue must have turned
up before and that at least a handful of people may be able to point me
in the right direction.
Ok, I was trying to debug some code where endl appearantly wasn't
doing it's job, or at least, did not seem to be inserting an '\n' into
the stream. I managed to crystalize the problem area into this snippet:
#include <ostream>
#include <iostream>
#include <fstream>
using namespace std;
#define USE_OWN_ENDL (0)
class test_stream: public ofstream
{
public:
test_stream() {}
};
template <typename T> test_stream &operator<<(tes t_stream &s, T t)
{
std::cout << t;
return s;
}
#if USE_OWN_ENDL
test_stream &operator<<(tes t_stream &s, test_stream &(*fp)(test_str eam
&))
{
return (*fp)(s);
}
test_stream &endl(test_stre am &s)
{
std::cout << endl;
return s;
}
#endif
int main(int argc, char **argv)
{
cout << "Directly from main:\n";
cout << "Hello world" << endl;
cout << "Hello again" << endl;
cout << "Using 'test_stream' class:\n";
test_stream new_stream;
(new_stream << "Hello world") << endl;
(new_stream << "Hello again") << endl;
}
Now, as written (USE_OWN_ENDL is 0), the program does not output any
newlines to the new_stream. If I set USE_OWN_ENDL to 1, my own endl
function is invoked via the overloaded operator<<(test _stream&,
test_stream& (*fp)(test_stre am&) call and it all works nicely. While
this is definitely possible, my guts are telling me there's a more
elegant way.
My feeling is that what is going on here is that since I've created my
own stream class, the base class operator<< does not come into play for
manipulators such as endl. Is it possible to define a suitable
operator<< that does this, so that I don't have to define my own endl?
I've tried various approaches that don't compile properly. Or is there
another approach to get this to work?
A related question: is this something that has changed in later years
because of a change in the standards or something? It seems to me that
the code I'm trying to work with must have worked (i.e. endls used as
described would have output '\n') at some time in some environment, and
it is only a couple of years old. So has endl worked in the way
expected because of a broken compiler or header file implementation at
some point?
Using g++ 3.3.5 (on Linux 2.6.8)
[Disclaimer: yes I know '\n' might be prefereble to endl, yes the
test_stream class doesn't do anything useful as it is written; I've
removed everything that's not related to the problem, the real class
adds some (slight) functionality to the stream]
/Ricard 4 1643 ri*****@axis.co m wrote:
My feeling is that what is going on here is that since I've created my own stream class, the base class operator<< does not come into play for manipulators such as endl. Is it possible to define a suitable operator<< that does this, so that I don't have to define my own endl? I've tried various approaches that don't compile properly. Or is there another approach to get this to work?
I can't answer your question.
But: The real question should be: Why do you want to derive
a new class from ofstream.
Usually that results in a lot of problems and is not necessary.
--
Karl Heinz Buchegger kb******@gascad .at
<ri*****@axis.c om> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com Hi!
I've tried to find an answer to this in the FAQ and elsewhere on the net, without success. I'm fairly sure that the issue must have turned up before and that at least a handful of people may be able to point me in the right direction.
Ok, I was trying to debug some code where endl appearantly wasn't doing it's job, or at least, did not seem to be inserting an '\n' into the stream. I managed to crystalize the problem area into this snippet:
#include <ostream> #include <iostream> #include <fstream>
using namespace std;
#define USE_OWN_ENDL (0)
class test_stream: public ofstream { public: test_stream() {} };
template <typename T> test_stream &operator<<(tes t_stream &s, T t) { std::cout << t; return s; }
#if USE_OWN_ENDL test_stream &operator<<(tes t_stream &s, test_stream &(*fp)(test_str eam &)) { return (*fp)(s); }
test_stream &endl(test_stre am &s) { std::cout << endl; return s; }
#endif
int main(int argc, char **argv) { cout << "Directly from main:\n"; cout << "Hello world" << endl; cout << "Hello again" << endl;
cout << "Using 'test_stream' class:\n"; test_stream new_stream; (new_stream << "Hello world") << endl; (new_stream << "Hello again") << endl; }
Now, as written (USE_OWN_ENDL is 0), the program does not output any newlines to the new_stream. If I set USE_OWN_ENDL to 1, my own endl function is invoked via the overloaded operator<<(test _stream&, test_stream& (*fp)(test_stre am&) call and it all works nicely. While this is definitely possible, my guts are telling me there's a more elegant way.
My feeling is that what is going on here is that since I've created my own stream class, the base class operator<< does not come into play for manipulators such as endl. Is it possible to define a suitable operator<< that does this, so that I don't have to define my own endl? I've tried various approaches that don't compile properly. Or is there another approach to get this to work?
Based on my reading of Josuttis (The C++ Standard Library, pp. 612ff), it
seems that there is an overloaded operator<< for ostream that handles endl
and other manipulators. To get your code to work as you wish, it seems that
you simply need to modify your overload so it picks up the stream
manipulators that are already defined. This means that the function pointer
needs to be in terms of ostream, not test_stream.
The following works on your code, but robustness is not guaranteed.
test_stream &operator<<(tes t_stream &s, ostream &(*fp)(ostre am &))
{
(*fp)(cout);
return s;
}
--
John Carson
Thanks John, that does fix the problem. Looking at it, it's almost too
obvious.
As for why the original stream class is derived from ofstream, well I
don't honestly know,
I'm just trying to get the code running again with as little effort as
possible (aren't we all :-) .
/Ricard ri*****@axis.co m wrote: I've tried to find an answer to this in the FAQ and elsewhere on the net, without success.
Exactly this question was discussed many times in this forum and
in comp.lang.c++.m oderated. Searching e.g. for "endl derived stream"
on <http://groups.google.c om/> turns up several useful results.
template <typename T> test_stream &operator<<(tes t_stream &s, T t) { std::cout << t; return s; }
This code is your problem: you *shall not* derive from 'std::ostream'
or its derived classes to change the output behavior! The *only*
reason to derive from 'std::ostream' is to create a convenience
interface for creating an 'std::ostream' with a derive stream buffer.
If you want to change the approach of output for a stream you shall
derive from 'std::streambuf '. Likewise for 'std::istream' and input.
More details and reasoning for this can easily be found by searching
past articles from me and/or James Kanze on the topic of stream
buffers.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: David Johnstone |
last post by:
Hi Group,
I am using gcc 3.2.2 on linux 2.4.19-4GB (SuSe 8.2).
I have a situation where I need to tie an ostringstream
to an istringstream so I can write to one and read back
what I wrote from the other. I had expected the code to
look like:
ostringstream* ostr_stdin = new ostringstream();
|
by: Christian Engström |
last post by:
When i compile the program listed below with gcc version 3.3.1 (MinGW on
Windows XP) I get the following result:
Calling 'func(d)':
'base' copy constructor
Calling 'func(*d_handle)':
'base' copy constructor
Calling 'func(d_handle)':
|
by: Eric Boutin |
last post by:
Hi all ! I'm currently writing a function that evaluate if there is a
diffence beetween 2 streams (istringstream and ifstream).
The problem is, it doesn't work. It *always* finds a difference at the
9th line because the first 8 lines are skipped, however, the is no
difference at all beetween the two streams, the only difference is that
after skipping the 8th first lines, one of the stream don't go forward
therefore a difference is...
|
by: Bangalore |
last post by:
Hi all,
I am finding quite difficulty in understanding the behaviour of the
following
program.
Base class is singleton, so it should allow the creation of only one
object.
Eventhough it is singleton , i tried to create three objects from it,
and I succeeded with only one object with address "0x1003b010"
|
by: utab |
last post by:
Dear all,
I tried to solve the occurence problem: to find the distinct occurences
of a word in an input. I know that I could use map and other STD lib
functions. I tried to do it the hard way. I tried sth and it is working
but I could not structure my algorithm very well so I had to add some
more lines after thinking it on a paper draft. I am posting the whole
code and waiting different ideas.
First I sorted them with the sort function,...
| |
by: iu2 |
last post by:
Hi all, can someone help me with this?
I'm trying to shorthen some logging function in our project, i.e.,
instead of
LogString("...);
use a more convenient
log() << "String here " << 12.33 << " and a number";
|
by: lmfmaw |
last post by:
Hi all,
I've hit the wall with this "fairly" simple problem. As you can see in
the code below, my destructors don't do their job as they are supposed
to (I left them empty for this example). I'm running the Visual Leak
Detector library (on VS 2005) to detect memory leaks and whatever I've
tried it still complains..
Please can someone help me clean up properly?
--------
|
by: yccheok |
last post by:
Hello all, I am confused on the correct assignment operator that
should be implemented on the derived class. I refer to the document
found at :-
http://www.icu-project.org/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html
which the author recommence not using "virtual" for assignment
operator. Hence, I provide the following implementation.
#include <iostream>
|
by: Eric |
last post by:
Ok...this seems to be treading into some really esoteric areas of c++.
I will do my best to explain this issue, but I don't fully understand
what is happening myself. I am hoping that the problem comes down to
standard c++ stuff and is not specific to Mac OS X compiler&linker.
I have put together a simple test project which can be found at:
http://ericgorr.net/LibraryLoading.zip
which demonstrates the problem.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |