Have a simple program, where I can insert a string into a statically defined array of strings of size 20.
This program worked just fine, until I was assigned to change it to use templates, so the code (with modificaiton) would support intergers or strings.
Using the Class “Shelf” in the included header, I can no longer declare the following object int main(), “Shelf book;” –as the compiler tells me book has not been declared and I’m missing Template Arguments.
#include<iostream>
#include<string>
#define shelfSize 20
template<class T>
class Shelf{
public:
Shelf();//default constructor
void insert(T&);
private:
string bookshelf[shelfSize];
int counter;
};
template< class T>
Shelf<T>::Shelf(){
for(int i=0; i <shelfSize; i++)
bookshelf[i]="";
counter=0;
}
template< class T>
void Shelf<T>::insert(T &booknum){
bookshelf[counter] = booknum;
counter++;
}
int main(){
Shelf book;
string isbn="";
cout<<"Enter ISBN Number you wish to enter into the Array: "<<endl;
getline(cin, isbn);
book.insert(isbn);
return 0;
}
Obviously, I watered down my program greatly and want to focus on what’s actually giving me an issue.
So as I said I get the following errors:
Missing Template arguements before “book”;
expect “;” before “book”.
“book” undeclared.
You need to specify a parameter to T. Templates need to be instantiated with the datatype passed as a parameter, like so: