Staypuft
Staypuft

Reputation: 129

Defining a new Object of a Class within a Template in C++, Error: Missing Template Arguments

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.

Upvotes: 1

Views: 144

Answers (3)

sergio
sergio

Reputation: 69027

You should use:

   Shelf<std::string> book;

now the template definition needs you to specify the type for which the template will be instantiated.

Anyway, it seems to me that you have not fully completed the template implementation, since your member:

   string bookshelf[shelfSize];

is still "hardcoded" as a string; you might want:

 T bookshelf[shelfSize];

with all the related changes that this requires (constructors, etc).

Upvotes: 2

MGZero
MGZero

Reputation: 5963

You need to specify a parameter to T. Templates need to be instantiated with the datatype passed as a parameter, like so:

Shelf<std::string> book;

Upvotes: 2

Grigor Gevorgyan
Grigor Gevorgyan

Reputation: 6853

You must provide the template argument to tell compiler which class of the template family to instantiate. Use Shelf<string> book; or Shelf<int> book;

Upvotes: 1

Related Questions