1

If you make a template class (or struct), and then inherit from it defining a class (struct), the following code is possible:

template <typename T>
struct Par
{
    T t;
};

struct Chl : public Par<int>
{
    void setT(int in) { t = in; }
};

int main()
{
    Chl c;
    c.setT(1);
}

However, if you make Chl a template too, like this

template <typename U>
struct Chl : public Par<U>
{
    void setT(U in) { t = in; }
};

int main()
{
    Chl<int> c;
    c.setT(1);
}

the compiler will give you an error:

error: ‘t’ was not declared in this scope
   12 |  void setT(U in) { t = in; }

To avoid it you have to define setT as follows:

void setT(U in) { this->t = in; }

and only then will it compile.

So it looks as if templating Chl creates some additional ambiguity which has to be resolved by this, but it doesn't seem to be the case (because the base struct has the same single field t in all cases). So why is this necessary (at least with g++)?

acalabash
  • 33
  • 5
  • 1
    Template classes can be specialized. Therefore, the compiler can not know that `t` means `this->t` for every possible base class `Par`. – Drew Dormann Jun 06 '22 at 18:43

0 Answers0