A question about using struct in STL

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jczhang

    A question about using struct in STL

    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()::STUDEN T' 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
  • Rob Williscroft

    #2
    Re: A question about using struct in STL

    jczhang wrote in news:bnln29$tsd $1@mail.cn99.co m:
    [color=blue]
    >
    > But if I move the typedef of STUDENT(line 6~9) out of function main,
    > the error will disappear. I wonder why.
    >
    >[/color]

    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.
    --

    Comment

    Working...