簡體   English   中英

Function 模板:實例化點和聲明點

[英]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 的模板的使用。 如果不是,那是什么?
  • Stroustrup 評論說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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM