template & STL

D

dawid

Hi, I'm trying to compile this template:

1 #include <set>
2
3 using std::set;
4
5 template <class TYPE>
6 void function(const set<TYPE> &data) {
7 for (set<TYPE>::const_iterator iter = data.begin(); iter !=
data.end(); iter++) {
8 }
9 }

g++ 4.2.3 prints:
g++ temp.cpp -o temp
temp.cpp: In function ‘void function(const std::set<TYPE,
std::less<_Key>, std::allocator<_CharT> >&)’:
temp.cpp:7: error: expected `;' before ‘iter’
temp.cpp:7: error: ‘iter’ was not declared in this scope
make: *** [temp] Error 1

What is wrong ??

regards
 
J

joe

Hi, I'm trying to compile this template:

  1 #include <set>
  2
  3 using std::set;
  4
  5 template <class TYPE>
  6 void function(const set<TYPE> &data) {
  7   for (set<TYPE>::const_iterator iter = data.begin(); iter !=
data.end(); iter++) {
  8   }
  9 }

g++ 4.2.3 prints:
g++     temp.cpp   -o temp
temp.cpp: In function ‘void function(const std::set<TYPE,
std::less<_Key>, std::allocator<_CharT> >&)’:
temp.cpp:7: error: expected `;' before ‘iter’
temp.cpp:7: error: ‘iter’ was not declared in this scope
make: *** [temp] Error 1

What is wrong ??

regards

You have to give the compiler a hint here.
Try adding the "typename" keyword :
for (typename set<TYPE>::const_iterator iter ...

It's just one of those things you have to train yourself to think of
when you see an error message like that in a template.
It's sort of like remembering when e comes before i.
Joe Cook
 
P

peter koch

Hi, I'm trying to compile this template:

  1 #include <set>
  2
  3 using std::set;
  4
  5 template <class TYPE>
  6 void function(const set<TYPE> &data) {
  7   for (set<TYPE>::const_iterator iter = data.begin(); iter !=
data.end(); iter++) {
  8   }
  9 }

g++ 4.2.3 prints:
g++     temp.cpp   -o temp
temp.cpp: In function ‘void function(const std::set<TYPE,
std::less<_Key>, std::allocator<_CharT> >&)’:
temp.cpp:7: error: expected `;' before ‘iter’
temp.cpp:7: error: ‘iter’ was not declared in this scope
make: *** [temp] Error 1

What is wrong ??

You forgot a typename: line 7 should read:
for (typename set<TYPE>::const_iterator iter = data.begin(); iter !
=

The reason is template specialisation: a template class could be
specialised, meaning that set<TYPE> might not have a const_iterator.
You and I know that this is silly for std::set, but the compiler does
not.

/Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top