Hello I'm having trouble converting a class to a template. It gives me two errors when I compile it. I cannot find whats wrong , but I'm pretty sure I did not write the template correctly.
#include "item.h"
#include<iostream>
usingnamespace std;
template<class T>
class Container
{
private:
void RemoveIndex(T id);
T items[100];
T counter;
T num; /////// the number of items in the array.
public:
void add_item(T New); /// Item New
void size();
void show();
T remove(T id); // int id
Container(); ////// constructor
};
#endif
#include <iostream>
usingnamespace std;
#include "auto.h"
#include "item.h"
#include "container.h"
Container<Item> shopping_cart;
int main()
{
// quick test for Item class I wrote, delete once you
// get how it works
Item i( 1000, "White bread", 0.99 );
Item y( 1993, "Dozen Eggs", 2.50 );
Item x( 2013, "cookies" , 3.00 );
shopping_cart.add_item(i);
// you'll use Auto in part 2, here's a quick example as well
/*
Auto a( 34, "Toyota", "Sienna", 2010 );
cout << a.toString() << endl;
*/
system("pause");
return 0;
}
template <class T>
T Container<T>::remove(T id)
{
for ( int i =0 ; i <counter ; i++ )
{
if ( items[i].getId() == id )
{
RemoveIndex (i);
returntrue;
}
}
returnfalse;
}
This is wrong, you have the return type as T, but you're returning bools from the function.
Templates look fine, but without knowing what the actual error messages are I can't help you much
EDIT:
1 2 3 4 5 6 7 8 9 10 11 12 13
template <class T>
T Container<T>::remove(T id)
{
for ( int i =0 ; i <counter ; i++ )
{
if ( items[i].getId() == id )
{
RemoveIndex (i);
returntrue;
}
}
returnfalse;
}
id is not the same type as the container is holding. It's a type that's defined in T. I assume ID is an int type, so I'd change that. And also, this container can now only be used on types that have a gedId() method.