GURKE
GURKE

Reputation: 153

Define type of variable with its own constant values

I want to create a new type of variable which has his own constant values. So I want to do something likes this: (This is a not working example to explain the idea)

class Variabletype {
public:
 static const uint8_t Option1 = 0;
 static const uint8_t Option2 = 1;
};

typedef const uint8_t Variabletype;

int main() {
    Variabletype vt = Variabletype::Option1;
    
    if (vt == Variabletype::Option1)
        printf("Option 1\n");
    else
        printf("Option 2\n");
        
    return 0;
}

I can't typedef the name Variabletype after declaring it as a class, but I hope it makes clear, what my intention is? The benefit of this idea would be finding directly the possible values of the variable, vt. I also don't want to spam my global space with constants, and I can not set vt to impossible values.

So is something like this possible? I already searched a lot but didn't find any solution.

Upvotes: 2

Views: 71

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51864

What you are looking for is an enumeration type – designed specifically for the purpose you outline. Although you can use a plain, 'C-style' enum, a more modern, C++ approach is to use a so-called "scoped enum"; see: Why is enum class preferred over plain enum?

Here's a possible implementation of your code using such a enum class definition:

#include <iostream>

enum class Variabletype : uint8_t { // You can specify the underlying type after the ":"
    Option1 = 0, // You can specify any 'actual' values you like ...
    Option2 = 1, // ... but the default uses values of 0, 1, 2 anyway
};

int main()
{
    Variabletype vt = Variabletype::Option1;

    if (vt == Variabletype::Option1)
        std::cout << "Option 1" << std::endl;
    else
        std::cout << "Option 2" << std::endl;

    return 0;
}

Upvotes: 4

Related Questions