Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c++ - Why do template classes allow member functions which cannot compile?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...