Linkage of templates

C

Chor Lit

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.
 
G

Gianni Mariani

Chor said:
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.

The short answer to this is "Because the standard says so".

However, perhaps some more insight would be that there is some level of
ambiguity and potential errors you can eliminate.

A.

struct S;
template <typename T> struct S
{
S & operator=( const S & ); // which S ?
};

B.

int X;

template < typename T>
struct X
{
// which X ?
X()
{
int y = X;
}
};
 
C

Chor Lit

Thanks Gianni.

I think this solve the ambiguity. But I am still not sure whether it is
valid.

A.

struct S;
template <typename T> struct S
{
::S & operator=( const ::S & ); // the global 'S', not struct S
};


B.

int X;

template < typename T>
struct X
{
// must be struct X , int X in this context is impossible
X()
{
int y = X; // no ambiguity.
}

}

I can't think of a counter example to support template name uniqueness
in a scope. Anyone can think of the reason ?

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top