0

I have stumbled upon a behavior of the g++ (6.2.1) compiler that I did not except. It seems that in some cases, g++ ignores errors in a template class when an erroneous definition of a function is not used.

Let's take this example:

class A
{
  bool _var;

  public:
    void myFunc() const
    {
      _var = true;
    }
};

int main()
{
  A a;

  return 0;
}

The compiler returns the following error:

error: assignment of member 'A::_var' in read-only object

Which is what I expected. Now let's make the class template:

template <typename MyType>
class A
{
  bool _var;

  public:
    void myFunc() const
    {
      _var = true;
    }
};

int main()
{
  A<int> a;

  return 0;
}

This compiles fine, even thought we are trying to assign a value to a member variable within a const method. Then, if I try to use the myFunc function, the compiler will see the error again and refuse to compile.

Why does this happen ? Shouldn't the compiler be able to see the error in every case ?

Thanks !

Shuny
  • 175
  • 1
  • 7

1 Answers1

4

This is happening because members of template classes are themselves templates, and as such, are only instantiated upon usage. And unused templates undergo only certain checks (so-called two-step instantiation).

SergeyA
  • 61,605
  • 5
  • 78
  • 137