{C++ etc.}

Latest Posts
 
Home | C++ Posts | Linux Posts | Programming Posts | Issue Tracking Posts

Wednesday, July 09, 2008

Inheriting from a Template Class


A class could be derived from a template class simply as follows;

template class
class A
{
int i_A;
}

template class
class B : public A
{

}

But when accessing member variables of the base class, a compiler error is given if it's done in the following manner;

template class
class B : public A
{
void Init(int i)
{
i_A = i;
}
}

the solution is to use "this->i_A" instead of "i_A" as per the GCC 3.4 release.

template class
class B : public A
{
void Init(int i)
{
this->i_A = i;
}
}

The reason for this is as follows (taken from GCC 3.4.0 release notes):


In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,

template struct B {
int m;
int n;
int f ();
int g ();
};
int n;
int g ();
template struct C : B {
void h ()
{
m = 0; // error
f (); // error
n = 0; // ::n is modified
g (); // ::g is called
}
};

You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,

template void C::h ()
{
this->m = 0;
this->f ();
this->n = 0
this->g ();
}

As an alternative solution (unfortunately not backwards compatible with GCC 3.3), you may use using declarations instead of this->:

template struct C : B {
using B::m;
using B::f;
using B::n;
using B::g;
void h ()
{
m = 0;
f ();
n = 0;
g ();
}
};

Full release notes...

No comments: