Deducing Types
Item 1:Understand template type deduction
template<typename T> |
there are three cases:
1.ParamType is a pointer or reference type,but not a universal reference.
2.ParamType is a universal reference.
3.ParamType is neither a pointer nor a reference.
Case1.ParamType is a pointer or reference type,but not a universal reference.
in this case,type deduction works likes this:
template<typename T> |
1.If expr’s type is a reference,ignore the reference part.
2.Then pattern-match expr’s type against ParamType to determine T.
we have these variable declarations.
int x=27; |
If we change the type of f’s parameter from T& to const T&,the constness
of cx and rx continues to be respected.
template<typename T> |
if param were a pointer (or a pointer to const) instead of a reference,things would work essentially the same way.
template<typename T> |
Case 2:ParamType is a Universal Reference
- If
expr
is an lvalue,both T and paramType are deduced to be lvalue reference. - if
expr
is an rvalue,the “normal” rules apply.
for example:
template<typename T> |
Case 3:ParamType is Neither a Pointer nor a Reference
In this case,we’re dealing with pass-by-value.
template<typename T> |
It’s easy to deal with this case,just ignore the reference ,const,volatile part.but we need recognize that const is ignored only for by-value parameters.
for example:
template<typename T> |
as we know,the const to the right of asterisk declares ptr to be const:ptr can’t be be made to point to a different location,nor can’t it be set to null.the const to the left of asterisk says that what ptr points to is const,hence can’t be modified.
so in accord with the type deduction rule for by-value parameters,the constness
of ptr will be ignored,the type deduced for param will be cosnt char
.
Array Arguments
As we know,array types are different from pointer types,in many contexts,an array decays
into a pointer to its first element.
for example:
const char name[]="TestName";//const char[8] |
if we pass an array to a template taking a by-value parameter,array type decays poninter,but if we pass references to arrays,what happens?
template<typename T> |
the ablitiy to declare references to arrays enables creation of a template that deduces the number of elements that an aray contains:
template<typename T,std::size_t N> |