21
votes
template <typename Z> Z myTemplate <Z> :: popFromVector ()
{
    if (myVector.empty () == false)
        return myVector.pop_back ();

    return 0;
}

int main ()
{
    myTemplate <int> obj;

    std :: cout << obj.popFromVector();

    return 0;
}

Error:

error: void value not ignored as it ought to be

AFAI can see, the return type of popFromVector is NOT void. What's the point that I am missing? The error disappears when I comment out this call in main().

3
Are you sure that's the error message from the compiler? What compiler are you using?Dani
The return value of std::vector<>::pop_back is however void. You want something like {Z x=myVector.back(); myVector.pop_back(); return x; } instead.user786653
What is myVector? What is the line with error?Maciej Piechotka
@user786653 That was helpful, thanks. If you post that as an answer, I'll accept that.Aquarius_Girl
@user786653 Now since you haven't responded...Aquarius_Girl

3 Answers

17
votes

std::vector<T>::pop_back() returns void. You attempt to return it as an int. This is not allowed.

8
votes

That is because the definition of std::vector::pop_back has a void return type ... you are trying to return something from that method, which won't work since that method doesn't return anything.

Change your function to the following so you can return what's there, and remove the back of the vector as well:

template <typename Z> Z myTemplate <Z> :: popFromVector ()
{
    //create a default Z-type object ... this should be a value you can easily
    //recognize as a default null-type, such as 0, etc. depending on the type
    Z temp = Z(); 

    if (myVector.empty () == false)
    {
        temp = myVector.back();
        myVector.pop_back();
        return temp;
    }

    //don't return 0 since you can end-up with a template that 
    //has a non-integral type that won't work for the template return type
    return temp; 
}
2
votes

It's the pop_back(). It has a void return type. You have to use back() to get the actual value. This is to avoid unnecessary copies.