Semantic correctness of non-instantiated C++ template functions

喜夏-厌秋 提交于 2019-12-05 08:55:38
quantdev

Bar is a non dependent name (i.e. its type does not depend on T), so the compiler is required to verify the correctness of the code during the first phase of name-lookup (see the note below).

Since Bar has no nonexistent_method() method, the compiler is required to issue a diagnosis.

If you change your template to:

template<typename T>
void foo(T t, T bar) {
    t.compiler_does_not_care();
    bar.nonexistent_method();
}

No non-dependent names are involved, so no error is emitted since the template is never instantiated (phase 2 of the lookup)


Notes:

  • Comprehensible description of two-phase name lookup from LLVM :

1) Template definition time: when the template is initially parsed, long before it is instantiated, the compiler parses the template and looks up any "non-dependent" names. A name is "non-dependent" if the results of name lookup do not depend on any template parameters, and therefore will be the same from one template instantiation to another.

2) Template instantiation time: when the template is instantiated, the compiler looks up any "dependent" names, now that it has the full set of template arguments to perform lookup. The results of this lookup can (and often do!) vary from one template instantiation to another.

  • As for the why non-dependent name lookup can't be deferred to the second stage, see this other SO post; it seems that it is mostly for historical reasons.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!