Re: C++ template
On Aug 6, 2:28 pm, "aman.c++" <aman....@gmail.com> wrote:
On Aug 6, 4:06 pm, Unkown to Xnntp <unkown@xnntp> wrote:
template <class Value> class Test1 {
public:
int a;
};
template <class Value> class Test2 : public Test1<Value> {
public:
void f() {
a = 2;
}};
the compiler (g++-4.0.1) says:
test.c: error: a was not declared in this scope
What is the problem
The problem is that Test1<Value> is a dependent base class and
the variable a is a non-dependent name.
As written, the compiler treats it as non-dependent. The author
of the code obviously wanted it to be dependent.
Compilers that use 2 phase lookup
In other words, compilers that conform to the C++ standard.
lookup the non-dependent names early but the dependent names
can't be resolved when parsing templates. The are resolved at
instantiation (ph 2). Hence the name a is ambiguous.
Not quite. First, the name isn't ambiguous; it isn't found,
because non-dependent lookup occurs at the point where the
template is defined, not where it is instantiated, and doesn't
take dependent base classes into account. (Note that if he'd
derived from Test1<int>, there'd be no problem.)
Dependent names are more complicated, and are searched both in
the context where the template was defined, and in the context
where it was instantiated, but only using ADL in the latter
case.
To resolve this you could make the name "a" also dependent
using either of:
Test1<Value> ::a = 2;
this->a = 2;
Yes. It's a shame that one has to resource to such tricks,
however, rather than simply being able to say what one means
(e.g. by explicitly declaring which names should be dependent).
For your case either line will work fine but there are
situations when one might be preferred over the other.
I think that the "this->" is the usual solution, and so it
should be preferred as long as there are no real reasons to do
otherwise.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34