4

I want to be able to pass an integer via command line argument that I will call length. I need to make this constant, because it will be used to determine the size of several bitsets. I have tried doing this many ways, for example:

int main(int arc, const char* argv[]){
        const int * ptr;
        if (!(istringstream{argv[1]} >> ptr)) { return 1;}
        const int length = *ptr;

        bitset<length> right_ones = 1;
        return 0;
}

I also tried it this way:

int main(int arc, const char* argv[]){
        int test_int;   
        if (!(istringstream{argv[1]} >> test_int)) { return 1;}
        const int length = argv[1];

        bitset<length> right_ones = 1;
        return 0;
}

But none of the ways I have tried it worked. How can I accomplish this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
partyphysics
  • 175
  • 7
  • 10
    If it's passed via a command line argument, it is obviously not constant. – harold May 09 '17 at 17:15
  • 1
    Get your DeLorean up to 88 mph. Run the program, observe the user's future input, then go back and add it. – molbdnilo May 09 '17 at 17:19
  • 2
    Templates can only be used with compile time constant. Values passing before running are obviously not compile time constants – phuclv May 09 '17 at 17:19
  • If this is meant to be a compile time constant, why don't you make it a compiler argument (like in a qmake project file, depending what you use) instead of a run time argument? – Aziuth May 09 '17 at 17:22
  • A template argument has to be compile-constant and hence can not be derived directly from a runtime value (cmdline argument). If you insist, you could use a switch and instantiate for several compile-time values – André May 09 '17 at 17:25
  • 1
    Unless it changes with C++17, you can use `std::vector`. In ways, it behaves more like a `bitset` than a `vector`, so I recall an intent to change it and introduce a new class to replace the functionality. – Weak to Enuma Elish May 09 '17 at 17:34
  • @JamesRoot correct [Why is vector not a STL container?](http://stackoverflow.com/q/17794569/995714) – phuclv May 11 '17 at 10:34

2 Answers2

4

If it is going to be passed as a command line argument, then you cannot make it a constant.

By the way, this is relevant to your case: Define bitset size at initialization?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
2

The length of the bitset is needed at compile time so no matter how you try it there is no way to pass that value at runtime.

grigor
  • 1,584
  • 1
  • 13
  • 25