Template deduction interesting case, c++ -
consider peace of code:
template<class t> void f(const t& t) { static int x = 0; cout<<++x<<endl; } int main() { int j = 0; const int = 0; f(5); f(i); f(j); } i have called function 3 types. although 5 , j can same thing, int, const int different type.
anyway output is:
1 2 3 so means compiler instantiates same function different types.
correct? can explain why?
from [temp.deduct.call]:
template argument deduction done comparing each function template parameter type (call p) type of corresponding argument of call (call a) described below.
p const t& , a int, int, , const int in 3 calls.
we have:
if p reference type, type referred p used type deduction.
p reference type, use p' == const t deduction against a == int or a == const int. in both cases, deduce t == int p' == const int (and p == const int&) , deduced a == const int. more cv-qualified original a first 2 calls, that's explicitly made ok:
in general, deduction process attempts find template argument values make deduced identical (after type transformed described above). however, there 3 cases allow difference:
— if original p reference type, deduced (i.e., type referred reference) can more cv-qualified transformed a.
thus, 3 cases call f<int>.
Comments
Post a Comment