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>() );
}
Of course it prints 10.
I have some basic idea of how templates and type deduction works, but i can't understand this code. What is the magic behind I
? How we know I
from int2type
instance passed to func
?
Template argument deduction is covered by section [temp.deduct.call] of the C++14 Standard. It is too big to reproduce in full, but the gist is that the compiler will compare the argument type int2type<10>
with the parameter type int2type<I>
and try to find a value for I
that makes both of those the same.
In [temp.deduct.type]/9 and /17 it is specified that the parameter class-template-name<i>
, where i
is a non-type template parameter, is matched by the argument class-template-name<n>
where n
is an argument of the same type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.