template <int T> struct int2type{};
template<int I>
void func( int2type<I> )
{
printf("int_val: %i\n", I);
}
int main(int argc, char *argv[])
{
func( int2type<10>() );
}
当然,它打印 10。
我对模板和类型推导的工作原理有一些基本了解,但是我听不懂这段代码。背后有I
什么魔力?我们如何I
从int2type
传递给的实例中知道func
?
C++14 标准的 [temp.deduct.call] 部分涵盖了模板参数推导。它太大而无法完整重现,但要点是编译器会将参数类型int2type<10>
与参数类型进行比较,int2type<I>
并尝试找到一个值I
,使两者相同。
在 [temp.deduct.type]/9 和 /17 中,指定了参数class-template-name<i>
wherei
是非类型模板参数,参数class-template-name<n>
wheren
是相同类型的参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句