Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do template classes allow member functions which cannot compile?

Tags:

c++

templates

class P
{
};

template< typename P >
class C : public P
{
  public:
  void f()
  {
    P::f();
  }
};

int main() {
  C<P> c1;
  return 0;
}

Just in case my question leaves any room for misunderstanding, here is a code example. If C was not templated but inherited from P directly, then the sample would fail to compile because clearly function f() attempts to call a function on base class P which is non-existent.

However if C is templated then this is only picked up if f() is actually called.

I'd like to know why there is this difference. In both instances f() would be dead code and stripped anyway, yet the program is ill-formed in the non-template scenario.

like image 845
qeadz Avatar asked Jul 09 '15 21:07

qeadz


2 Answers

Actually, the program you posted is not ill-formed. While the "implicit instantiation" C<P> c1; instantiates all member declarations,

the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist

[N4140, 14.7.1(2)] Since you never use C<P>::f, its definition is never needed and thus never instantiated.

This is different to an "explicit instantiation" like

template class C<P>;

which would instantiate the definition of all members of C<P> and thus result in an error.

like image 76
Baum mit Augen Avatar answered Sep 18 '22 11:09

Baum mit Augen


Because it makes sense to allow to use only the functions that are actually well formed.

Take vector::push_back(const T&), that requires T to be copyable. But you can still use most of vector even if T is a movable non-copyable type.

like image 29
sbabbi Avatar answered Sep 17 '22 11:09

sbabbi