Re: non-const reference to temporary
Dave Harris wrote:
chris.morley@lineone.net (Chris Morley) wrote (abridged):
You can cast like blargg says but (if I had to and didn't use MS
compilers) I'd do it like this rather than embedded in the call...
void WriteEverythingToFile( const File& file, const std::string&
text)
{
File& myfile = const_cast<File&>(file);
myfile.write(text);
}
An alternative is to just overload the function to take a filename:
void WriteEverythingToFile( File &file, const std::string &text );
void WriteEverythingToFile( const char *name, const std::string &text ) {
File myfile( name );
WriteEverythingToFile( myFile, text );
}
Now you can call with:
WriteEverythingToFile( "filename.txt",
std::string("stuff to write") );
which makes the short case even shorter, and doesn't involve unsafe
const_casts, mutable etc.
That's not always possible or desirable; in fact, I often find it
much more flexible to have the subroutine accept a stream reference
parameter (std::istream& or std::ostream&) instead of a filename,
because that allows the subroutine to work on any kind of streams.
A typical pattern occurring very often looks like this:
void subroutine(std::istream&);
int main(int argc, char** argv)
{
if (argc < 2)
subroutine(std::cin);
else while (++argv, --argc) {
if (std::strcmp(*argv, "-") == 0)
subroutine(std::cin);
else {
std::ifstream f(*argv);
if (f)
subroutine(f);
else
std::cerr << *argv << ": " << strerror(errno) << '\n';
}
}
}
where you can call subroutine() with either a std::ifstream object
or std::cin.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]