[英]need help understanding the C++ code
I came across this piece of code in "C++ Templates - The complete Guide". 我在“ C ++模板-完整指南”中遇到了这段代码。 I tried my best to find out if this has been explained somewhere. 我尽力找出这是否已经在某处得到了解释。 Apologies if it has already been explained 抱歉,如果已经解释过
template<int I> void f(int (&)[24/(4-I)]);
template<int I> void f(int (&)[24/(4+I)]);
int main()
{
&f<4>; // ERROR: division by zero (SFINAE doesn't apply)
}
Book does say that this won't compile for a specific reason but I do not understand the template syntax and how the function is called with & operator at the beginning. 书中确实说这不会由于特定原因进行编译,但是我不了解模板语法以及一开始如何使用&运算符调用函数。
Appreciate the help. 感谢帮助。
Harish 哈里什
In fact, it does compile. 实际上,它确实可以编译。 You can also call one of these functions, eg the following prints +
: 您也可以调用以下功能之一,例如以下打印+
:
template<int I> void f(int (&)[24/(4-I)]) { std::cout << "-" << std::endl; }
template<int I> void f(int (&)[24/(4+I)]) { std::cout << "+" << std::endl; }
int main()
{
int a[3];
f <4>(a);
}
Anyhow, both template functions f
expect a reference to an int
array, whose length depends on template parameter I
. 无论如何,两个模板函数f
希望引用一个int
数组,该数组的长度取决于模板参数I
For instance, I picked a[3]
because 24/(4+I) = 24/8 = 3
for I=4
. 例如,我选择a[3]
是因为对于I=4
24/(4+I) = 24/8 = 3
。
The function is not called by &f<4>
, but only instantiated by taking its address (which actually issues a warning for the unused result). 该函数未由&f<4>
调用,而仅通过获取其地址进行实例化(实际上会为未使用的结果发出警告)。
I guess the book assumes the code won't compile due to the division by zero caused by attempting to instantiate the first overload for I=4
, which is not the case. 我猜这本书假设代码由于尝试实例化I=4
的第一个重载而导致的除以零而无法编译,但事实并非如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.