When I try to compile the code
istream in;
if (argc==1)
in=cin;
else
{
ifstream ifn(argv[1]);
in=ifn;
}
gcc fails, complaining that operator=
is private. Is there any way to set an istream
to different values based on a condition?
You could use a pointer for
in
, e.g.:You can replace cin's streambuf with another, and in some programs this is simpler than the general strategy of passing around istreams without referring to cin directly.
Even though it's extremely rare to use cin after control leaves main, the above try-catch avoids undefined behavior if that's something your program might do.
You cannot affect streams like this. What you want to achieve can be obtained using a pointer to an istream though.
So, is it not complaining "no appropriate constructor available" ? Anyways, you can modify it as below.