This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Compiler chokes on a simple template - why?
- From: Jonathan Wakely <cow at compsoc dot man dot ac dot uk>
- To: Topi Maenpaa <topiolli at ee dot oulu dot fi>
- Cc: gcc at gcc dot gnu dot org
- Date: Thu, 17 Mar 2005 10:07:55 +0000
- Subject: Re: Compiler chokes on a simple template - why?
- References: <200503171033.54907.topiolli@ee.oulu.fi>
On Thu, Mar 17, 2005 at 10:33:54AM +0200, Topi Maenpaa wrote:
> Hi,
>
> Here is a snippet that does not compile with gcc 3.4.1 (on Mandrake 10.1).
>
> ---------------------------------------------------
> template <class T> class A
> {
> public:
> template <class U> void test(T value) {}
> };
>
> template <class T> void test2(A<T>& a, T val)
> {
> a.test<int>(val);
This needs to be:
a.template test<int>(val);
> }
>
> int main()
> {
> A<int> a;
> a.test<int>(1); //works fine
> }
> ---------------------------------------------------
>
> $ g++ -o test test.cc
> test.cc: In function `void test2(A<T>&, T)':
> test.cc:9: error: expected primary-expression before "int"
> test.cc:9: error: expected `;' before "int"
Because test2 is a template it doesn't know what A<T> is (in the general
case) so you need to tell the compiler that a.test is a function template,
otherwise it is parsed as a member variable, giving "a.test less-than int",
which doesn't make sense.
> The funny thing is that if I change the name of the "test2" function to
> "test", everything is OK. The compiler complains only if the functions have
> different names. Why does the name matter?
That I'm not sure about ...
I would have expected it to fail with the same error when the function
is called "test" - but I'd be wrong apparently.
> The code compiles if "test2" is not a template function.
Because in that case the compiler knows the full definition of A and
knows that a.test refers to a function template, not a member variable
(for instance).
> Furthermore, calling
> A<T>::test directly from main rather than through the template function works
> fine.
Again, in that context the compiler knows that a.test is a function
template.
> I don't know if this is really a compiler thing, but it's hard to imagine the
> standard would impose such behavior.
Yes, it's ugly. No, it's not a bug. It's required by the standard :-(
jon
--
"I find television very educating. Every time somebody turns on the set,
I go into the other room and read a book."
- Groucho Marx