[英]Function template: point of instantiation and declaration
我对 Stroustrup C++ 第 4 版第 749-750 页的代码有疑问。 此代码试图显示实例化绑定点。 Stroustrup 在此代码之前说: “对给定模板集 arguments 的每次模板使用定义了一个实例化点。对于 function 模板,该点(实例化)位于最近的全局或命名空间 Z31A1FD210BE4BEF2D11在包含该用途的声明之后。” .
void g(int); template<typename T> void f(T a) { g(a); // g is bound at a point of instantiation } void h(int i) { extern void g(double); f(i); } // point of declaration for f<int>
关于此代码的问题:
f(i)
吗? 它是对一组给定 arguments 的模板的使用。 如果不是,那是什么?f<int>
的“声明点”在h() {}
之后。 声明点与实例化点不同吗?以下所有标准参考均指N4659:2017 年 3 月 Kona 后工作草案/C++17 DIS 。
实例化点是
f(i)
吗? 它是对一组给定 arguments 的模板的使用。 如果不是,那是什么?
不,虽然在这个例子中f(i)
以一种需要它存在的方式引用f<int>
特化,特化的实例化点紧跟在void h(int)
的定义之后,因为void h(int)
的定义是第一个引用专业化的定义,根据[temp.point]/1 :
For a function template specialization , a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization and the context from which it is引用取决于模板参数,特化的实例化点是封闭特化的实例化点。 否则,这种特化的实例化点紧跟在引用特化的命名空间 scope 声明或定义之后。
Stroustrup 评论说
f<int>
的“声明点”在h() {}
之后。 声明点与实例化点不同吗?
是的,声明点与实例化点不同。 从[temp.inst]/4和[temp.inst]/8 :
[temp.inst]/4 Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist . [...]
[temp.inst]/8如果function 模板或成员 function 模板特化以涉及重载解析的方式使用,则特化的声明被隐式实例化([temp.over])。
前者还取决于重载决议,而 function 模板可以在不涉及重载决议的情况下被实例化(例如显式实例化)。 正如[temp.point]/8所涵盖的,function 模板的特化可能在一个翻译单元内有多个实例化点,但给定特化的声明自然只会在单个翻译单元内生成一次(如所涵盖上面:第一次在重载决议的上下文中使用)。
在您的特定示例中, f(i)
在h
中的调用将隐式实例化f<int>
并导致f<int>
的声明,因为调用涉及重载决议,但这些机制由不同的管理,尽管相关,但规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.