tags:

views:

126

answers:

5

Hello,

I declared a struct for some options that shall be filled by command line arguments or by reading an input file:

struct options {
  int val1;
  int val2;
  bool val3;
}

Now I want to check for the correct number of arguments at execution of the program. Sure thing a

const int optionsSize = 3;

would do. But is there any adaptive way? What if I add another value into the struct and don't remember to increase the integer?

+7  A: 

Why not add the options as specified into an std::vector<string> options and use the options.size() method to check the correct number. Then convert them to the proper datatype.

A more robust way of doing this kind of thing would be to use Boost Program Options

RC
Thanks for giving a solution AND pointing out an alternative via boost!
Gunnar
A: 

There is no way to compute this number inside the language. Basically your only option is to write a script to look at the source. If all the elements in your struct have the same type, you can use sizeof(thestruct)/sizeof(commontype).

Helmut
A: 

I am not aware of any way of determining the number of members in a struct at runtime. You have two options:

  1. Use a boost fusion sequence, but this is overkill
  2. Use boost program_options, and here for each option I believe you can specify whether it should be mandatory or not. And this will automatically check for you (while parsing the command line). So all you need to remember to do is to add the struct member to the set of options for program_options. There are lots of examples in the docs, ask if you have any issues...
Nim
+3  A: 

This would require reflection, which C++ doesn't have.

So in your case, the code that parses the command line, checks for syntax errors, and sets the requested values in your struct will also have to check whether enough values are set.

sbi
A: 

"What if I add another value into the struct and don't remember to increase the integer?"

Then the unit testing is rather deficient if it doesn't detect that.

Cheers & hth.,

Alf P. Steinbach