Templates and local variables

| 2 Comments

Can anyone spot what's wrong with this code?


void foo( void )
{
  struct Test {
    int a;
  };

std::vector< Test * > tests;
tests.push_back( new Test );
}

Here's a hint: it compiles fine in Visual Studio, but not in XCode. The real answer lies in section 14.3.1.2 of the C++ language specification. Namely,

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.

I was entirely unaware of this little factoid until I recently committed some code at work which bounced back to me as being unable to compile on the Mac. After reading this section though, I see now that gcc is conforming to the standards more strictly by default than Visual Studio is (though both IDEs have options for strict/relaxed conformance).

My question is: why? It strikes me as being rather odd that templates behave this way, since (AFAIK) there is no other language construct in C++ which disallows locals in this manner. Any ideas as to the reasoning behind this?

2 Comments

To confuse and confound you. Well, not you personally, rather all C++ programmers. Apparently, that is not a good enough reason (sounded fine to me, but I don't get a vote - fortunately). I think it has been removed in the latest spec (09?).

Leave a comment

August 2009

Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31