Do all method declarations in a class that has a template parameter need to be declared with that parameter? The compiler seems to want something like the following
// Queue.h
template <class ItemType>
class Queue
{
Queue();
ItemType dequeue();
int count();
/* ... other methods ... */
};
// Queue.cpp
template <class ItemType>
Queue<ItemType>::Queue()
{ /*...*/ }
template <class ItemType>
int Queue<ItemType>::count()
{/*...*/}
template <class ItemType>
ItemType Queue<ItemType>::dequeue()
{/* ... */}
Coming from Java/C#, this seems a bit redundant–I feel like I should be able to define the methods more like this:
int Queue::count()
The signature does not reference ItemType, so we can omit it.
Queue::ItemType Queue::dequeue()
The signature references ItemType, but the compiler knows that we’re talking about the template parameter because we qualify the identifier with Queue::
Yes, you need to provide the template argument. Note that while it might look redundant, it is not. C++ templates are a much more powerful tool that Java generics, and they allow for specializations. That means that with a base template
Queuethere might be multiple implementations that match different template arguments and have different definitions. Alternatively, you can have a singleQueuetemplate with multiple specializations for some functions. These two situations require you to provide both thetemplateargument list an the class template arguments: