Brans Ds
Brans Ds

Reputation: 4117

Enum with associated value

I have an Enum with operators different operators.

enum OperatorsTypes
    {
        Zero, Division, Equal, If, Minus, Multiplication, One, Plus, RandomNumber, Time
    };

Each operator have different contacts count. For instance Plus - 2 contacts count, Random number - zero. What is the base way to store and use contacts counts assotiated with opetators.

I considered 3 options:

1) Using array with index ewual to OperatorsTypes and value = contacts count.

2) Using following declaration:

enum OperatorsTypes
    {
        Zero = 0, Division = 12, Equal = 21, If = 32, Minus = 42, Multiplication = 52, One = 60, Plus = 72, RandomNumber = 81, Time = 90,
    };

where first digit is Id number and second - contacts count. Then using % operator in some static method i can find operator's contacts count from OperatorsTypes value.

3) Using switch in some static method

But all this approach has drawbacks... (note - that my code must be top speed). Is there better way for this task in C++ both beatifull and top-speed?

Upvotes: 2

Views: 1145

Answers (1)

IdeaHat
IdeaHat

Reputation: 7881

one way to do what you want is inline template functions:

template <OperatorsTypes o>
inline int GetOperatorContacts();

template<>
inline int GetOperatorContacts<Zero>() {return 0;}

template<>
inline int GetOperatorContacts<Minus>() {return 2;}

//...ect

In C++11, you could even make these constexpr, but I don't have a ton of experience with that.

However, this is probably an X vs Y problem. I'd be guessing you want a heck of a lot more information than just the number of contacts, and that a structure or a class is a better fit than an enum.

Upvotes: 1

Related Questions