Home > OS >  How to use enum as starting args with aliases
How to use enum as starting args with aliases

Time:01-05

I am trying to use enum as starting args. It should works as aliases pairs so "i" and "info" should have same value, etc...

I know it is possible to use if/else with flags, but i would like to done this using for eg. switch with int value.

#include <iostream>
#include <string>

namespace startFlags {
    enum class flag {
        i, info = 0,
        e, encrypt = 1,
        d, decrypt = 2,
        c, check = 3,
        h, help = 4
    };

    void printFlag(startFlags::flag input) {
        std::cout << "Output: " << input << std::endl; //error
    }
}

Is there any other way to deal with starting args with aliases.

CodePudding user response:

You need to cast enum classes if you'd like to print them as int (or something else) even though the underlying type is int:

Example:

#include <iostream>

namespace startFlags {
    enum class flag {
        i, info = i,    // both will be 0
        e, encrypt = e, // both will be 1
        d, decrypt = d, // ...
        c, check = c,
        h, help = h
    };

    void printFlag(startFlags::flag input) {

        // Note cast below:

        std::cout << "Output: " << static_cast<int>(input) << '\n';
    }
}

int main() {
    printFlag(startFlags::flag::i);
    printFlag(startFlags::flag::info);
}
  •  Tags:  
  • Related