Some problems with the template
template<class TypeIterator>
void Generate(const TypeIterator& first, const TypeIterator& last)
{
//do something
}
When I tried to call the generate function like this:
PhanSo arr[10];
Generate(arr, arr+10);
I got the error: void Generate (const TypeIterator &, const TypeIterator &) ': template parameter' TypeIterator 'is ambiguous
When I used:
PhanSo arr[10];
Generate(&arr[0], &arr[10]);
Then my program was executed successfully.
I tried to fix this by removing the "&" in the function parameter
template<class TypeIterator>
void Generate(const TypeIterator first, const TypeIterator last);
Then there is no mistake. Can anyone explain this to me?
source to share
The array is not a pointer. The array name used as a pointer to the first element of the array is just syntactic sugar .
If the template parameter is a reference , there will be no conversion between arrays and pointers.
When you called void Generate(const TypeIterator& first, const TypeIterator& last)
with Generate(arr, arr+10);
, it arr
resolves to PhanSo[10]
, and arr+10
goes to PhanSo*
, which has actually been pointed out by both the g ++ compilers and Microsoft as an ambiguity.
When you called void Generate(const TypeIterator& first, const TypeIterator& last)
with Generate(&arr[0], &arr[10]);
, things became much clearer to the compiler because you are specifically supplying the element with the address of the elements, so the TypeIterator allows PhanSo*
.
Finally, when you called void Generate(const TypeIterator first, const TypeIterator last)
with Generate(arr, arr+10);
, since the template parameter is no longer a reference , the normal array to pointer conversion takes place and TypeIterator
resolved PhanSo*
.
Thanks for reading.
source to share
When you call Generate(arr, arr+10);
-
first
will beconst PhanSo (&)[10]
. - but
second
decomposes into a pointer:const PhanSo *
.
and hence the type mismatch.
Since an array cannot be passed by arr
fading value too much for a pointer if you have
template<class TypeIterator>
void Generate(const TypeIterator first, const TypeIterator last);
without reference.
source to share