1

I know that options can be added when initializing an instance of fstream, for example:

fstream file("filename.txt", ios::in | ios::out | ios::binary);

In this case there are 3 options. I have several questions:

  1. How should I implement that in my own function?
  2. Should I define any const values or marcos?
  3. How to parse the options and deal with the them properly?
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • **Bitmask** is the word you are searching for. – user1810087 Aug 18 '17 at 15:37
  • 5
    `|` **is not** the logical OR. It is the ["bitwise OR"](http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators) and it is a completely different thing. But the [bitwise operators](http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators) are what you need. – axiac Aug 18 '17 at 15:40

2 Answers2

3

How should I implement that in my own function?

Make it a bitmask type:

The bitmask type supports a finite number of bitmask elements, which are distinct non-zero values of the bitmask type, such that, for any pair Ci and Cj, Ci & Ci != 0 and Ci & Cj == 0. In addition, the value 0 is used to represent an empty bitmask, with no values set.


Should I define any const values or macros?

The values are typically constants representing consecutive powers of two, i.e. 1, 2, 4, 8, 16, etc.

How to parse the options and deal with the them properly?

You never need to "parse" these options - all you need to do is to check if a given option is present or not. You can do it with & operator:

openmode x = ios::in | ios::out;
if (x & ios::in) {
    ... // TRUE
}
if (x && ios::binary) {
    ... // False
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

These are bitmasks.

How should I implement that in my own function?

Should I define any const values or marcos?

No need for macros. I prefer enums:

namespace options {
    enum options_enum : unsigned {
        in       = (1u << 0),
        out      = (1u << 1),
        binary   = (1u << 2),
        whatever = (1u << 3),
    };
};

How to parse the options and deal with the them properly?

By masking:

bool in = option_argument & options::in;
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326