Topic: Linkage of templates
Author: "Chor Lit" <chorlit@gmail.com>
Date: Wed, 19 Apr 2006 11:19:47 CST Raw View
I read Nicolai and David's book "C++ templates" and they mention, on
page 99, that every template must have a name that is unique within its
scope. The following is the example they gave:
int C;
class C; //ok: class names & nonclass names are in a different
"space"
int X;
template < typename T>
class X; //Error:conflict with variable X
struct S;
template <typename T>
class S; //Error:conflict with struct S
Can anyone explain why does template names must be unique ? What is the
rationale behind this restriction imposed by the language ? Since int C
and class C can share the same name, I don't see why the name 'X' and
'S' above can raise any conflict.
Thanks.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: AlbertoBarbati@libero.it (Alberto Ganesh Barbati)
Date: Thu, 20 Apr 2006 01:31:37 GMT Raw View
Chor Lit ha scritto:
>
> int X;
>
> template < typename T>
> class X; //Error:conflict with variable X
>
> Can anyone explain why does template names must be unique ? What is the
> rationale behind this restriction imposed by the language ? Since int C
> and class C can share the same name, I don't see why the name 'X' and
> 'S' above can raise any conflict.
I think the restriction was introduced to simplify the parser, because
the use of the angular bracket can lead to ambiguities. Consider this:
template <int N> class X { operator int(); };
int X; // (1) illegal
int Y = X<0>(); // (2) ???
int Z = X<0; // (3) ???
If line (1) were legal, then the parser would have big problems in
parsing (2) and (3). In both cases the first three tokens "X<0" can be
interpreted either as a boolean expression (if X is the variable) or the
beginning of a template-id (if X is the template-name). Detecting which
case from the context requires the parser to perform some kind of
backtracking, thus adding extra complexity that is not worth the effort.
The other case:
> struct S;
>
> template <typename T>
> class S; //Error:conflict with struct S
is less obvious, I think it was introduced just for consistency and
because it's the Right Thing(tm). In fact I think that having a
(non-template) class and a variable with the same name is not good
programming style and it's tolerated only because of backward
compatibility and compatibility with C. Remember that in C the "struct"
in "struct C" cannot be omitted, so there is no ambiguity there.
Ganesh
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]