何时需要实例化功能模板定义? [英] When is required instantiation of function template definition?
问题描述
在我阅读完此问题的答案后,我仍然在提问.答案讨论的是[temp.point]中定义的实例化点的位置,但是如果需要实例化,则不会进行评估.
After I read the answer for this question, I am still asking question. The answer talks about location of point of instantiation as defined in [temp.point] but it is not evaluated if the instantiations are required.
[temp.inst] 指定何时需要函数模板专门化实例化,一般规则是:
[temp.inst] specifies when a function template specialization instantiation is required, the general rule is:
实现不得隐式实例化函数模板,变量模板,成员模板,非虚拟成员函数,成员类等,除非需要此类实例化.
此外,在本部分的标准中,声明的实例化和定义的实例化是分开考虑的.
Moreover in some paragraph of this section of the standard, instantiation of declaration and instantiation of definition are considered separately.
让我们考虑以下代码:
static void Yeap0(int);
template <class T>
void Yeap(T a){
Yop(a);
}
template <class T>
auto Yeap2(T a){
Yop(a);
return 0;
}
namespace x{
struct y{};
}
int main() {
Yeap0(0);//ok no definition required here
x::y ax{};
Yeap(ax); //the declaration is sufficient,
Yeap2(ax); //need to deduce auto => definition required
//compilation error
return 0;
}
namespace x{
void Yop(y){}
}
static void Yeap0(int){}
Gcc,Clang和MSVC仅对Yeap2(ax)
产生错误,抱怨说Yop
在Yeap2实例化时未定义.
Gcc, Clang and MSVC produce only an error for Yeap2(ax)
, complaining that Yop
is not defined at the point of instantiation of Yeap2.
但是不会为Yeap(ax)
生成此错误.从基本的角度来看,这似乎是合乎逻辑的,对于无模板功能Yeap0
,仅需要声明.
But this error is not generated for Yeap(ax)
. From basic consideration this seems logical, only the declaration is needed, as for the none template function Yeap0
.
但是 [temp.inst]/4 的演讲让我感到困惑.可以理解,Yeap
的实例化也是必需的.但是似乎编译器走了一条更聪明的路.
But the lecture of [temp.inst]/4 let me perplex. It could be understood that the instantiation of Yeap
is also required. But it seems that compilers have taken a more clever path.
编译器的行为是扩展吗?
Is the compilers behavior an extension?
注意:我将不接受无需诊断"答案.这将是对情报的侮辱:是否可以相信3个编译器已经特别注意为Yeap(ax)
这样的情况关闭诊断,而对于Yeap2(ax)
不是这种情况?
Note: I will not accept the "no diagnostic required" answer. This would be an insult to intelligence: Could one believe that 3 compilers have taken special care to shut down diagnostics for case like Yeap(ax)
but not for Yeap2(ax)
?
推荐答案
编译器抱怨的真正原因是该函数返回auto
.
The compiler complaining really comes from the fact that the function returns auto
.
在auto
情况下,您确实击中
除非需要此类实例化.
必须来自要求 dcl.spec.auto >.
要验证评估,您可以在代码Yeap2中替换为:
To verify that assessment you can replace in your code Yeap2 by:
template <class T>
auto Yeap2(T a){
Yeap(a);
return 0;
}
并且没有编译错误.
这篇关于何时需要实例化功能模板定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!