tags:

views:

69

answers:

1
#include <iostream>
#include <vector>

int main()
{
    class Int {
        public:
            Int(int _i) : i(i) {}
        private:
            int i;
    };

    std::vector<Int> VI;
}

I try to compile the above code and got the following error message:

foo.cc: In function 'int main()':
foo.cc:13: error: 'main()::Int' uses local type 'main()::Int'
foo.cc:13: error:   trying to instantiate 'template<class _Alloc> class std::allocator'
foo.cc:13: error: template argument 2 is invalid
foo.cc:13: error: invalid type in declaration before ';' token

could anyone of you tells me why I can't do things like this in CPP? thanks in advance.

+5  A: 

The standard explictly prohibits using local classes to instantiate templates in 14.3.1[temp.arg.type]/2.

A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.

This will be changed in C++0x.

David Rodríguez - dribeas
@David : thanks, but why?
Haiyuan Zhang
@Haiyuan: because the standard says so.
Prasoon Saurav
I don't know about the reasons towards the decision in the past, but the fact that they have changed that limitation in C++0x seems to imply that the reasons were not so strong or needed to be overcome for other language features that were introduced --think lambdas, that actually create function objects in place.
David Rodríguez - dribeas
AFAIK the old problem was with template instantiation. The compiler needs to decide whether `std::vector<Int>` is already instantiated, when it sees the definition of `VI`. That means it needs to be able to precisely identify _which_ definition of `Int` was used to instantiate that particular `std::vector<Int>`. You effectively need a unique mangled name for `Int`. In the example above, you could have something like `__main__Int`, but with nested unnamed scopes this is even harder.
MSalters