473,803 Members | 3,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help needed for STL ifstream class

I've posted this in another thread, but I suppose I should've started a
new thread for it instead.

I cannot get the following short program to compile under g++:

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main(int argc, char **argv)
{
copy(istream_it erator<char>(ar gc >= 2 ? ifstream(argv[1]) : cin),
// this line won't compile!
istream_iterato r<char>(),
ostream_iterato r<char>(cout)) ;

return 0;
}

The compiler error messages are as followed:

/usr/include/c++/4.0.0/iosfwd: In copy constructor
'std::basic_ios <char, std::char_trait s<char::basic_i os(const
std::basic_ios< char, std::char_trait s<char&)':
/usr/include/c++/4.0.0/bits/ios_base.h:779: error:
'std::ios_base: :ios_base(const std::ios_base&) ' is private
/usr/include/c++/4.0.0/iosfwd:55: error: within this context
/usr/include/c++/4.0.0/iosfwd: In copy constructor
'std::basic_ist ream<char, std::char_trait s<char::basic_i stream(const
std::basic_istr eam<char, std::char_trait s<char&)':
/usr/include/c++/4.0.0/iosfwd:61: warning: synthesized method
'std::basic_ios <char, std::char_trait s<char::basic_i os(const
std::basic_ios< char, std::char_trait s<char&)' first required here
a.cpp: In function 'int main(int, char**)':
a.cpp:10: warning: synthesized method 'std::basic_ist ream<char,
std::char_trait s<char::basic_i stream(const std::basic_istr eam<char,
std::char_trait s<char&)' first required here
a.cpp:10: error: no matching function for call to
'std::istream_i terator<char, char, std::char_trait s<char>,
ptrdiff_t>::ist ream_iterator(s td::basic_istre am<char,
std::char_trait s<char)'
/usr/include/c++/4.0.0/bits/stream_iterator .h:70: note: candidates are:
std::istream_it erator<_Tp, _CharT, _Traits,
_Dist>::istream _iterator(const std::istream_it erator<_Tp, _CharT,
_Traits, _Dist>&) [with _Tp = char, _CharT = char, _Traits =
std::char_trait s<char>, _Dist = ptrdiff_t]
/usr/include/c++/4.0.0/bits/stream_iterator .h:66: note:
std::istream_it erator<_Tp, _CharT, _Traits,
_Dist>::istream _iterator(std:: basic_istream<_ CharT, _Traits>&) [with
_Tp = char, _CharT = char, _Traits = std::char_trait s<char>, _Dist =
ptrdiff_t]
/usr/include/c++/4.0.0/bits/stream_iterator .h:62: note:
std::istream_it erator<_Tp, _CharT, _Traits, _Dist>::istream _iterator()
[with _Tp = char, _CharT = char, _Traits = std::char_trait s<char>,
_Dist = ptrdiff_t]

Now, I have discovered that if I change the program into the following,
then it compiles fine:

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main(int argc, char **argv)
{
istream *ifile = argc >= 2 ? new ifstream(argv[1]) : &cin;
copy(istream_it erator<char>(*i file),
istream_iterato r<char>(),
ostream_iterato r<char>(cout)) ;

return 0;
}

I know this works, but it would be nice to understand why the original
version does not work anyway.

Thank you for your help.

--

-kira

Oct 6 '07
12 2701
Kira Yamato wrote:
On 2007-10-06 00:46:28 -0400, Kai-Uwe Bux <jk********@gmx .netsaid:
>Kira Yamato wrote:
>>If so, is there a good reason why the C++ designer chose it this way?

It helps avoiding some issues arising from integral promotion. Otherwise,
it is just a nuisance. For instance, you can do:

MyClass & operator= ( MyClass const & other ) {
MyClass( other ).swap( *this );
return ( *thid );
}

but not

MyClass & operator= ( MyClass const & other ) {
this->swap( MyClass( other ) );
return ( *this );
}
You also cannot use a temporary to initialize a default non-const
parameter:

void search ( SearchClass & initial_pos = SearchClass() );

but if you provide a member function

class SearchClass {
...

SearchClass & me ( void ) {
return ( *this );
}

};

you can do:

void search ( SearchClass & initial_pos = SearchClass().m e() );

And for standard classes that do not support a me() method, you could do:

void grow ( std::vector<int & the_list =
( std::vector<int >() = std::vector<int >() ) );

Since the assignment operattor returns a non-const reference, the result
will happily bind to the parameter.

As you can see, it is not very logical at all.
The next version of the standard will include r-value references which
hopefully will put an end to this nonsense.
>>As far as I know, a temporary object lives on the stack, and there
should be no reason why it should not be modified.

There isn't and you can modify temporaries at will. You just cannot bind
them to non-const references directly.

Best

Kai-Uwe Bux

Thank you for your very detailed explanation.

It's beginning to dawn on me that many rules in C++ can be bent.

For example, your code above shows a way to "bind" a temporary object
to a non-const reference (by using the returned value of the operator =
).
Be careful when bending the rules :-)

For instance, binding a temporary to a non-const reference is subject to
livetime issues. The following is not good:

int_vector & iv = ( int_vector() = int_vector() );

The reason is that the temporary int_vector is destroyed right away. For
const-references, the standard makes a special guarantee that the temporary
that is bound to the reference (which may not be the one you think it is)
lives as long as the reference.

The reason that you can use these tricks to bind a temporary to a parameter
in a function call expression is that the temporary is guaranteed to live
as long as the maximal enclosing expression. As for initializing the
default parameter, I am actually not sure (I think I checked it once and
convinced myself that it is OK, but my memory might play a prank on me).

In another thread I started last week, someone showed me how to declare
a const member function that can modify its own member variable without
using 'volatile'
you mean 'mutable'
nor 'const_cast'. Essentially, his code was as follow:

class Obj
{
private:
Obj *that;
int state;

public:
Obj() : that(this), state(0) {}

void changeMe() const
{
that->state++; // changing state!
}
};
Now, that is evil (and if the object was actually declared const, it is also
undefined behavior).
Best

Kai-Uwe Bux
Oct 6 '07 #11
On Oct 6, 4:49 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Barry wrote:
[..]
As "? :" need the second and third expression to be of the same type
I believe it's not that strict.
Not at all. Ignoring the special case where one of the second
or third expressions is a throw expression, the rule for class
types is that one one of the types must convert to the other.
One typical use is initializing a pointer to Base with one of
two different derived, and this requires an explicit cast, since
there is no attempt to convert both to some common third type.
long double a = rand() 5 ? 42 : 3.14159;
Here 42 is 'int' and 3.14159 is 'double'. The requirement is that
the types of the expressions should be such that either the second
can be converted to the first or vice versa.
I'ts a bit more complicated than that:-). In the case of
arithmetic or enumeration types, the "usual arithmetic
conversions" rule applies. Otherwise, of course, the above
would be ambiguous: int converts to double, and double converts
to int.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Oct 6 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
354
by: Revman | last post by:
I'm having problems opening and reading from a file to test a Class. My diver main.cpp is fairly short but with a longer file open function // Project #4 -- Main/driver program #include "daytime.h" #include <string> #include <fstream>
4
3740
by: hall | last post by:
Hi. I ran across a bug in one of my problems and after spending some time tracking it down i found that the problem arose in a piece of code that essentially did this: ----------- ifstream in("in.txt"); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";} in.close(); if(!in) {cout << "error\n";}
5
8987
by: Dr. Ann Huxtable | last post by:
Hello All, I am reading a CSV (comma seperated value) file into a 2D array. I want to be able to sort multiple columns (ala Excel), so I know for starters, I cant be using the array, I need something more sophistictated like a vector of row objects. The data is of this format (same number of columns for each row): A, x, y, z, ...
3
2673
by: Drewdog | last post by:
I am getting some error messages which I can't figure out their meaning. I have the code setup, I think it's correct but it doesn't work. My goal is to get this program to read from a data file and basically put it into an output file that I can access as a test file. Here is my header file: #include <iostream.h> #include <fstream.h> #include <iomanip.h>
8
2622
by: acheron05 | last post by:
Hi there, Hopefully I won't fit the stereotype of the typical student posting his assignment to be written for him, but I am quite stuck. If anyone could give me some help in how to create dynamic objects (which inherit from a base class) and storing them in a vector, it would be absolutely wonderful at this point. I think from there I might be able to sculpt the rest of the program without (too much) trouble. I'll post what I've been...
2
7478
by: pretear_yuki | last post by:
I'm a 14 year old student in Singapore. I am doing a programming for my Research Studies in school, I got the source codes of my programme from my mentor in the National University of Singapore Infocomm Research department. However, when I tried to compile the codes, I get the error message that says: "no matching function for call to `Englingo::addEnglingo(std::vector<int, std::allocator<int> >)' " The error is in the Englingo.cpp: #include...
31
3154
by: Martin Jørgensen | last post by:
Hi, I've had a introductory C++ course in the spring and haven't programmed in C++ for a couple of months now (but I have been programmed in C since january). So I decided to do my conversion utility in C++, before I forget everything. But it doesn't compile: ------------
10
2254
by: B. Williams | last post by:
I have an assignment that requires me to write a program that uses a class, a constructor, a switch, and store the records in a text file. The second requirement is to create a function called updatePower which will search through the file looking at the names and if a name is a match, will allow you to replace the integer stored for power. I have written the program and completed the first task, but I need some assistance on the secind....
3
2314
by: Stephen Torri | last post by:
Below is a class that is suppose to represent a segment of memory or a contents of a binary image (e.g. ELF executable). I have started to read Modern C++ Design and thought the best way to ensure I was understanding the chapter on policy classes was to attempt to apply them to my project. I understand the general concept of policies but I lack the knowledge and wisdom of how to identify them in an existing project. So I figured to get an...
0
9700
marktang
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...
0
9564
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,...
0
10546
Oralloy
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...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
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...
1
7603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4275
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
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.