Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compiler does not detect error in class template

Consider the following example:

template <class T>
  class C
{
  public:
    C();
    C(C&& rhs);
  private:
    T m_data;
};

template <class T>
C<T>::C()
: m_data(T())
{
}

template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
}

int main()
{
    C<int> i;
}

Line : m_data(rhs.data) contains an error as C does not have a member named data. But none of the compilers that I tried (gcc 5.2, clang 3.5.1) detected that error.

But when I add the following line to main function the compiler detects the error:

C<int> j = std::move(i);

Why the compiler does not give an error in the first case?

Even if that particular function is not called it can figure out that C has no member named data.

In addition when I change the definition of move constructor to the following:

template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
  data = 0;
}

the compiler gives error on line data = 0; but not on : m_data(rhs.data). So the function gets parsed.

like image 784
Hrant Avatar asked Nov 30 '22 00:11

Hrant


1 Answers

There is 2 passes to check error in template.

  • One for non dependent code
  • One for dependent code (done at instantiation)

Your code is template dependent, so it is checked only when the method is instantiated.

like image 102
Jarod42 Avatar answered Dec 04 '22 13:12

Jarod42