A question about using struct in STL

J

jczhang

Hi,
I have a question when using STL. Look at this piece of code:
1 #include <vector>
2
3 using namespace std;
4
5 int main() {
6 typedef struct student {
7 char* name;
8 int age;
9 } STUDENT;
10 typedef vector<STUDENT> STUDENT_VECTOR;
11 STUDENT_VECTOR students;
12 }
When I compile it using gcc3.2, the compiler complains:

tmp.cxx: In function `int main()':
tmp.cxx:10: template-argument `main()::STUDENT' uses local type `
main()::STUDENT'
tmp.cxx:10: template argument 2 is invalid
tmp.cxx:10: ISO C++ forbids declaration of `STUDENT_VECTOR' with no type

But if I move the typedef of STUDENT(line 6~9) out of function main, the error will disappear.
I wonder why.

Thank you!
-- jczhang
 
R

Rob Williscroft

jczhang wrote in
But if I move the typedef of STUDENT(line 6~9) out of function main,
the error will disappear. I wonder why.

Its a requirment of the language, local classes do not have external
linkage (importantly they don't have a unique name), template arguments
are required to have external linkage.

If this wern't the case then you could end up with two source file's
being compiled seperatly and then linked together that both define
std::vector< local_type > even though both types are different, i.e.
a mess that your linker isn't going to be able to sort out.

HTH.

Rob.
 

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

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top