I converted this StrNode class to a template class, and now I am trying to convert the List portion but cannot get it to match up. Any one have some ideas?
#include <iostream>
usingnamespace std;
#include "StrList.h"
int main() {
cout << "\n*** StrList Test ***" << endl;
StrList<string> list;
list.add("zero");
list.add("one");
list.add("two");
list.add("three");
list.add("four");
list.add("five");
list.print();
list.add(1, "added at position 1");
list.add(0, "added at position 0");
list.add(4, "added at position 4");
list.print();
cout << "removing at indexes 3, 0" << endl;
list.remove(3);
list.remove(0);
list.print();
list.add(2, "added at position 2");
list.print();
cout << "five is at index " << list.indexOf("five") << endl;
cout << "two is at index " << list.indexOf("two") << endl;
return 0;
}
You are only specifying a type for the function parameter, so you are not using data sent:
1 2 3 4 5 6
template<typename C>
void StrList<C>::add(int index, C /*data*/) { // should make data a const & instead
StrNode<C>* newNode = new StrNode/*<C>*/(C); // should be creating a copy of "data" instead here
}
Could also consider moving StrNode into StrList, as both require the same template parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
template< class T >
class List
{
struct Node
{
Node* next;
T data;
Node( T const & _data, Node* _next = NULL ) : data(_data), next(_next)
{
}
T& getData(); // your accesor returns a COPY, when it should return a reference, can just keep this class encapsulated than there is no need for an accessor
};
};
template<typename C>
void StrList<C>::add(int index, C /*data*/) { // should make data a const & instead
StrNode<C>* newNode = new StrNode/*<C>*/(C); // should be creating a copy of "data" instead here
}
When you say i should make data a const&, do you mean that i should change it to (int index, const& data)? Either way, when I try and use a double for a second list declaration in Main i get an error saying that you cannot convert const char[20] to double??
Compiler...
1 2 3 4 5 6 7
main.cpp(20): error C2664: 'void List<C>::add(int,C)' : cannot convert parameter 2 from 'const char [20]' to 'double'
1> with
1> [
1> C=double
1> ]
1> There is no context in which this conversion is possible
right i was trying to use const& as a template, either way completely wrong. After reviewing it I was able to use your help to compile and run, now I just have to test some other types. Also the struct Node idea was helpful too so thanks for that.