mmirzadeh
mmirzadeh

Reputation: 7079

What is the order of compilation for templated objects?

Sorry could not find a better title for my question. Basically what I noticed was the following compiles fine:

#include <vector>

void foo();

int main () {
    foo();
    return 0;
}

namespace{
struct point {
        double x, y;
    };
}

void foo(){       
    std::vector<point> p;
}

whereas compiler complains about the following:

#include <vector>

void foo();

int main () {
    foo();
    return 0;
}

void foo(){
    struct point {
        double x, y;
    };       
    std::vector<point> p;
}

// g++ output:
a.cpp: In function ‘void foo()’:
a.cpp:14: error: template argument for ‘template<class _Tp> class std::allocator’ uses local type ‘foo()::point’
a.cpp:14: error:   trying to instantiate ‘template<class _Tp> class std::allocator’
a.cpp:14: error: template argument 2 is invalid
a.cpp:14: error: invalid type in declaration before ‘;’ token

I want to know what is wrong with the second approach? Isn't struct point completely defined at the point of creating a new std::vector<point> object?

Upvotes: 2

Views: 71

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234514

This is due to a limitation in C++03 (now lifted in C++11), that simply forbids the use of local types (i.e. types defined in function bodies) as template arguments.

Upvotes: 8

Related Questions