0

I am writing a program which converts postfix arithmetic expressions to infix ones using a stack. The user input is a string, which is split into an array (treating spaces as delimiters). Then a case statement for "+", "-", "*" and "/" distinguishes between operators and operands (i.e. if it's not one of those symbols, it's an operand; so typecast to integer).

I was wondering whether it's possible to create something similar to an enum, where the admissible types are either integers, or the symbols +, -, * and /?

1
  • 2
    You probably want a Token class that represents whatever you want. Then either subclass it for OperatorToken and NumberToken so you can put them all on the same stack, or use something simpler like isOperator(), where the integer would then have the value of OPERATOR_PLUS, OPERATOR_MINUS, etc. Commented Mar 17, 2017 at 15:57

2 Answers 2

3

This is a good use case for std::variant -- or its doppelgänger boost::variant.

enum class Operator : char { plus = '+', minus = '-', multiply = '*', divide = '/' }; // Now a token can contain either an integer or an operator. using Token = std::variant<int, Operator>; 
Sign up to request clarification or add additional context in comments.

2 Comments

a little enchancement can be made enum class Operator: char
@em2er why not. Thanks!
0

Is it possible to create something similar to an enum, where the admissible types are either integers

No.

An enum is internally a value of a C++ basic type. You cannot have integer and symbols there, except maybe if you reserve a few numbers interpreted as those symbols.

Other alternatives

Sure: Union or struct may solve this issues.

2 Comments

So is it not possible to create a hybrid datatype allowing integers and only those four symbols?
No, they must be of an Integral type which do not includes struct or equivalent. If you have enough with 32bit integer, you may use a 64bit integer and use additional bits for this purpose.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.