vendredi 27 octobre 2017

C++11: return either ifstream or istream?

I have a program I would like to take either a file (specified in arguments) or cin as input.

That end, I have written the following function:

istream get_stream(string * filename) {
    if (!(filename->empty())) {
        ifstream fs = get_open_filestream(filename);
        istream& is = fs;
        return is;
    } else {
        check_cin();
        return cin;
    }
}


The sub functions are correct and throw the errors I need them to throw.


Next, I try to receive the output:

istream input_stream;
try {
    input_stream = get_stream(&filename); <-- fails
} catch (bad_input_exception e){
    cerr << e.what();
    return 0;
}


However, this fails completely, with the following errors:

  1. error: call to deleted constructor of 'istream' (aka 'basic_istream')
  2. error: no matching constructor for initialization of 'istream'

These errors occur at the following locations:

istream get_stream(string * filename) {
    if (!(filename->empty())) {
        ifstream fs = get_open_filestream(filename);
        istream& is = fs;
        return is;     <---------------------------------- 1
    } else {
        check_cin();
        return cin;    <---------------------------------- 1
    }
}


istream input_stream; <----------------------------------- 2
try {
    input_stream = get_stream(&filename); <-- fails
} catch (bad_input_exception e){
    cerr << e.what();
    return 0;
}


I have been searching for a solution for this, and the answers I have run into seem to all suggest this should be possible via polymorphism. However, I think I am getting some detail wrong (additionally, I have tried variations on receiving it, but I haven't had success).

Aucun commentaire:

Enregistrer un commentaire