|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||
| learning cpp (9) | |
|
I defined a class template and function templates. I hope to print all types with the funciton: template <typename T> void MyQueue<T>::Print() { std::vector<int>::iterator It1; It1 = data.begin(); for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ ) cout << " " << *It1<<endl; } by using vector template. Now it just works for int. How can I change it to work for typename T std::vector<typename T>::iterator It1; always failed. Thank you! ///////////////////////////////////////// #include <iostream> #include <vector> #include <string> using namespace std; template <typename T> class MyQueue { std::vector<T> data; public: void Add(T const &); void Remove(); void Print(); }; template <typename T> void MyQueue<T> ::Add(T const &d) { data.push_back(d); } template <typename T> void MyQueue<T>::Remove() { data.erase(data.begin( ) + 0,data.begin( ) + 1); } template <typename T> void MyQueue<T>::Print() { std::vector<int>::iterator It1; It1 = data.begin(); for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ ) cout << " " << *It1<<endl; } //Usage for C++ class templates int main() { MyQueue<int> q; q.Add(1); q.Add(2); cout<<"Before removing data"<<endl; q.Print(); q.Remove(); cout<<"After removing data"<<endl; q.Print(); MyQueue<string> str; str.Add("stirng1"); str.Add("string2"); cout<<"Before removing data"<<endl; str.Print(); str.Remove(); cout<<"After removing data"<<endl; str.Print(); return 0; } | |
|
|
|
| kbw (3827) | |||
You've specialised the vector in the template to int, you should pass in T.
| |||
|
|
|||
| learning cpp (9) | |
When I changed std::vector<T>::iterator It1;sI got those compiling errors: template.cpp: In member function ‘void MyQueue<T>::Print()’: template.cpp:28: error: expected `;' before ‘It1’ template.cpp:29: error: ‘It1’ was not declared in this scope template.cpp: In member function ‘void MyQueue<T>::Print() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]’: template.cpp:55: instantiated from here template.cpp:28: error: dependent-name ‘std::vector<T,std::allocator<_CharT> >::iterator’ is parsed as a non-type, but instantiation yields a type template.cpp:28: note: say ‘typename std::vector<T,std::allocator<_CharT> >::iterator’ if a type is meant | |
|
|
|
| jsmith (5804) | |||
Use
Better yet use const_iterator and make Print() a const member function. | |||
|
|
|||
| kbw (3827) | |
|
I get the same error when I compile under GCC 3.4.x. I'll try it on 4.x when I get home. It compiles fine with Visual Studio 2005. | |
|
|
|
| learning cpp (9) | |
|
Thanks jsmith and kbw. Now it works with typename std::vector<T>::iterator It1; | |
|
|
|