I have an exercise wherein I must use a template class "Garage" that takes as parameters either a "car" or a "bike". Easy enough but I keep getting errors since I obviously don't understand the templates well enough. Is this :
template<class Car>
class Garage{
Car array[10];
public:
void addCar(int counter1);
void removeCar(int counter1);
void displayContents(int counter1);
};
template<class Motorbike>
class Garage{
Motorbike array[10];
public:
void addMotorbike(int counter2);
void removeMotorbike(int counter2);
void displayContents(int counter2);
};
proper ? Do I have to insert the template infront of every function of the class ? The program of course contains more classes and functions but its the template thing I need to get sorted out in my head. Thanks for taking the time.
CodePudding user response:
I dont understand how you think templates would work. If you had to write out specifically every implementation for each instantiation then there would be no need for templates in the first place. You could name your classes CarGarage
and MotorbikeGarage
and call it a day. You probably want something along the line of this:
template<class VehicleType>
class Garage{
VehicleType array[10];
public:
void addVehicle(int counter1);
void removeVehicle(int counter1);
void displayContents(int counter1);
};
From this class template (it is not a template class, there are no template classes. Garage
is a template, not a class) you can instantiate the types Garage<Car>
which has an array of Car
s as member and a Garage<Motorbike>
which has an array of Motorbike
s as member.
Implementations of the member functions need to be in the header (see Why can templates only be implemented in the header file?). And it is easiest to define them inline within the template.