1

Edit: Added token struct/enum to code block

I'm new to c++, so forgive me if I missed something obvious. I'm trying to write a c++ version of the Shunting Yard Algorithm, but it won't compile because it gives me the error: "cannot convert from 'void' to 'Token' (on the line I marked)." Can anyone tell me why it gives this error?

typedef enum TokenType { None, Number, Operator, LeftParens, RightParens };

struct Token
{
    enum TokenType type;
    union
    {
        int num;
        char op;
    };
};

list<Token> DoShuntingYard(list<Token> tokenList)
{
    stack<Token> opStack;
    list<Token> output;
    while (!tokenList.empty())
    {
        ****(This Line) Token t = tokenList.pop_front();
        switch (t.type)
        {
        case Number:
            output.push_back(t);
            break;
        case Operator:
            if (!opStack.empty())
            {
                Token op2 = opStack.top();
                if ((IsLeftAssoc(t) && GetOpPrecedence(t) <= GetOpPrecedence(op2)) || (!IsLeftAssoc(t) && GetOpPrecedence(t) < GetOpPrecedence(op2)))
                {
                    output.push_back(opStack.pop());
                }
            }
            break;
        }
    }
}

2 Answers 2

4

The problem is that pop_front does not return a value. If you want to remove the first element and read its value, you can do so in two steps:

Token t = tokenList.front();
tokenList.pop_front();

This convention is employed throughout the STL, mostly for efficiency reasons. By having front return the value and pop_front return nothing, you can capture the value if you want, but if you just want to remove the value you can do so without making an unnecessary copy of the removed object by just calling pop_front.

You will run into a similar error later on with this code:

output.push_back(opStack.pop());

To fix this, split this into two lines:

output.push_back(opStack.top());
opStack.pop();

Hope this helps!

1
  • In addition to the "convenience" there is also the possibility of the copy constructor throwing an exception while returning a value. If that happened during x = pop_front(), the value would be lost!
    – Bo Persson
    Jul 24, 2011 at 11:23
4

It gives you the error because std::list<>::pop_front() is a void function. It doesn't return anything. Yet, you are using it as if it returns something. So, the question is really to you: why are you attempting to use a void function as a value-returning function? What do you mean by Token t = tokenList.pop_front() line?

If you were trying to "pop" the first element from the list, the possible sequence of steps would include

Token t = tokenList.front();
tokenList.pop_front();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.