C++实例化点:要求或定义?
当函数模板被隐式实例化时,是声明还是所需模板的定义?
看来编译器只需要声明:
template <typename T>
T f();
int g() {
// Compiles OK, even though f's definition is not available here.
return f<int>();
}
template <typename T>
T f() {
return 123;
}
int main()
{
std::cout << g();
}
我正在努力查看标准中指定此行为的位置。谁能帮忙找到这个?
例如,“ temp.point”条款不是说F的实例化点应立即遵循G的定义,这应该导致编译误差,因为尚未定义F?
&lt; ...&gt;这种专业的实例化点 遵循名称空间范围声明或定义 这是指专业。
When a function template is implicitly instantiated, is the declaration or the definition of the template required?
It seems that compilers only require a declaration:
template <typename T>
T f();
int g() {
// Compiles OK, even though f's definition is not available here.
return f<int>();
}
template <typename T>
T f() {
return 123;
}
int main()
{
std::cout << g();
}
I'm struggling to see where this behavior is specified in the Standard. Could anyone help finding that?
For example, doesn't the "temp.point" clause say that the point of f's instantiation should immediately follow g's definition, which should lead to compilation error as the f is not defined yet?
<...> the point of instantiation for such a specialization immediately
follows the namespace scope declaration or definition
that refers to the specialization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要有一个模板声明其专业化被推荐的程序是有效的。在您的情况下,您提供了
f
的模板声明,该模板可以由编译器使用来知道要拨打哪个专业化。但是,定义可以在以后提供(如您所做的),并且需要呼叫成功(而不是要求呼叫以绑定到函数)。此外,专业化的实例化
f&lt; int
将在g
之后,如以下示例中使用的注释所强调的。在下面的示例中,点标记为#1
是专业f&lt; int
的POI。还要注意,从 temp.point#7 :
这意味着将有第二个POI标记为
#2 < /code>在以下给定示例中,相同的专业化
f&lt; int&gt;()
。因此,
#1
和#2
下面标记的都被视为专业化的POI。As long as there is a template declaration whose specialization is referred the program is valid. In your case, you have provided a template declaration for
f
that can be used by the compiler to know which specialization to call. The definition however can be provided later(as you did) and which is needed for the call to succeed(and not for the call to be bound to a function).Moreover, the point of instantiation for the specialization
f<int>
will be just afterg
as highlighted in the below example using comments. In the below sample, point labeled#1
is the POI for the specializationf<int>
.Note also that from temp.point#7:
This means that there will be a second POI labeled as
#2
in the below given example for the same specializationf<int>()
.Thus both
#1
and#2
labeled below, are considered POI for the specialization.