By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,092 Members | 1,650 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,092 IT Pros & Developers. It's quick & easy.

c++ template function error, expected constructor, destructor, or type conversion

P: 5
I have the following code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <list>
  3.  
  4. using namespace std;
  5.  
  6. template <typename T>
  7. list<T>::iterator doStuff( list<T>::iterator myIter  ) //--error here
  8. {
  9.   list<T>::iterator iter = myIter;
  10. .
  11.  do_some_stuff
  12.  .
  13.  return iter;
  14.  }
  15.  
  16.  
  17. int main() {
  18.  ....
  19.   doStuff(anIterator);
  20. ...
  21. }
  22.  
While compiling it by gcc 4.2.2, I got this error message:
error: expected constructor, destructor, or type conversion before 'doStuff'
I searched online for some help and I added "typename" before <list T>
at the line labeled "--error here". Then error then became:
template declaration of ‘typename std::list<T, std::allocator<_CharT> >::iterator doStuff’
expected `)' before ‘myIter’

But if I don't use the STL list, i.e., use my own defined class name,
Expand|Select|Wrap|Line Numbers
  1. template <typename T>
  2. typename myClass<T>::iterator doStuff(myClass<T>::iterator myIter)
  3.  
then the program can be compiled.

What should I know to define/use template function/class? It looks like the problem lies
somewhere between the standard class and my own class.
What should I do to get the original program working?
Jan 25 '08 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
list<T> is called a dependent type. According to the C++ standard, if a dependent type is to be used as a type, then you must use the typename keyword.\

This should do it:
Expand|Select|Wrap|Line Numbers
  1. template <typename T>
  2. typename list<T>::iterator doStuff( typename list<T>::iterator myIter  )
  3. {
  4.   typename list<T>::iterator iter = myIter;
  5. .
  6.  do_some_stuff
  7.  .
  8.  return iter;
  9.  }
  10.  
Jan 25 '08 #2

P: 5
list<T> is called a dependent type. According to the C++ standard, if a dependent type is to be used as a type, then you must use the typename keyword.\

This should do it:
Expand|Select|Wrap|Line Numbers
  1. template <typename T>
  2. typename list<T>::iterator doStuff( typename list<T>::iterator myIter  )
  3. {
  4.   typename list<T>::iterator iter = myIter;
  5. .
  6.  do_some_stuff
  7.  .
  8.  return iter;
  9.  }
  10.  
Yes, it works now.
Thanks very much.
Jan 25 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.