Reputation: 181
I am creating a template class with a list object as a private member:
.
.
.
private:
list<E> listObject;
};
The first constructor has to create a list object with capacity of 10. How would you do that?
template<class T, class E>
Queue<T,E>::Queue()
{
listObject.resize(10);
}
or
template<class T, class E>
Queue<T,E>::Queue()
{
listObject = new list<E>(10);
}
or any other idea?
Upvotes: 0
Views: 3926
Reputation: 1
Currently, no setting capacity api is provided. Its max-size() returned is a super large integer, just a theorial value. api resize
will actually allocate that specified N size elements with default value (or object constructor), not just reserve N elements space.
If u want to support a capacity, maybe you should inherit std::list, maintain a capacity value in your implemented child template class.
Upvotes: 0
Reputation: 227438
The most idiomatic option would be to initialize the list with the desired size. This is done in the constructor initialization list:
Queue<T,E>::Queue() : listObject(10)
{
....
}
This will leave you with a list of 10 default constructed objects (whether you actually need that is a different matter).
Note that in C++11 you can initialize data members at the point of declaration. So you could also do this:
template <typename T, typename E> Queue
{
....
list<E> listObject = list<E>{10};
};
More on std::list
here.
Upvotes: 1
Reputation: 4673
There is a constructor for list that takes a size argument. You can call that constructor in your class's constructor using an initializer list
template<class T, class E>
Queue<T,E>::Queue()
: listObject(10)
{}
If you need information, search and learn about initializer lists. You can read more about the std::list
class's constructors on a reference website -- that's what I did here -- although I admit the long series of constructors is a little bit much when you're first getting started.
That page says the following about this constructor, with only a count specified (assuming C++11): "Constructs the container with count value-initialized (default constructed, for classes) instances of T."
Upvotes: 0