0

I've recently had to implement the common pattern of reading from a file or, given a filename of "-", from stdin. There is an abundance of solutions on SO, but I found mine to be shorter.

string from (some arg);
ifstream fromfile;
istream& read = (from == "-")
    ? cin
    : (fromfile.open(from), fromfile);

Key part is moving fromfile.open to a branch. This lets us use a reference instead of a pointer while avoiding checking for equality with "-" twice, which happens in most other solutions.

However, I did not find this kind of approach used anywhere else. I presume that is mainly because it is somewhat harder to read. Or is there something else?

mafu
  • 31,798
  • 42
  • 154
  • 247
  • 1
    shorter != more elegant – SuperStormer Feb 03 '22 at 01:58
  • 1
    @SuperStormer Certainly not in general. But in this case it is short and still easy to read (I think?) – mafu Feb 03 '22 at 02:24
  • *This lets us use a reference instead of a pointer while avoiding checking for equality with "-" twice* where does this check normally happen twice? Can you provide an example of this? – JohnFilleau Feb 03 '22 at 02:50
  • 1
    It is legal. Do you have any particular concerns? – Eugene Feb 03 '22 at 03:42
  • @JohnFilleau similarly to e.g. https://stackoverflow.com/a/19171123/39590, assigning to the `istream&` is a bit cumbersome. – mafu Feb 03 '22 at 05:37
  • @Eugene I do not. Just a bit confused because I could not find this pattern being used. – mafu Feb 03 '22 at 05:39
  • Personally, I don't consider this code to be elegant at all (more like "short and ugly") and would never use this form. Code which defines a variable that is potentially never used more effort than alternatives to reason about what it does. – Peter Feb 03 '22 at 07:31
  • This is one of those situations where a pointer feels more appropriate than a reference. Wrap it in a singleton-type function, and then use only takes one line of code. – JohnFilleau Feb 03 '22 at 13:51
  • @Peter Regarding the variable that is never used, I don't think that can be avoided? – mafu Feb 03 '22 at 15:22
  • @mafu - Not with your approach, no. With alternatives to achieve the same effect - which you claim to have read - it can. – Peter Feb 03 '22 at 22:16

0 Answers0