tags:

views:

67

answers:

1

I want to use a stack to store indices of an array,so I use the following typedef,where istack is a template class for stack:

typedef istack<size_t> IndexStack;

and I declare a stack by

IndexStack    stack;

But when I call the following function (where A.size() returns a size_t);

stack.push_back(A.size());

GCC gives the following error

sort.cpp: In function 'void quicksort2(Array&)':
sort.cpp:50:27: error: no matching function for call to 'istack<unsigned int>::push_back(size_t)'
iarray.h:103:8: note: candidate is: void istack<T>::push_back(T&) [with T = unsigned int]

How can I make it work?

+5  A: 
#include <cstddef>
template <class T>
struct istack
{
    void push_back(T& value);
    std::size_t size() const;
};

int main()
{
    typedef istack<size_t> IndexStack;
    IndexStack    a, stack;
    stack.push_back(a.size());
}

This code produces an error

In function 'int main()':
13 no matching function for call to 'istack<unsigned int>::push_back(size_t)'
note 5 candidates are: void istack<T>::push_back(T&) [with T = unsigned int]

Note that it lists candidates. (I suspect you are not reading / posting the entire error message.)

The given candidate doesn't match the call, because the reference is non-const. A temporary (such as the result of a.size()) cannot be bound to a non-const reference.

push_back should be taking a const T& value

UncleBens
That's the problem.push_back doesn't take const reference.By the way I forget to paste the third line of error message.Thanks very much for your answer.
luoq