krazyd
February 23rd, 2009, 10:26 AM
I have an implementation of the 'find' C++ standard library function:
// first implementation
template <class In, class X>
In find ( In begin, In end, const X& x ) {
while (begin != end && *begin != x)
++begin;
return begin;
}This seems to be correct and runs as expected. My question is, why does the following implementation not work?
// second implementation
template <class In>
In find ( In begin, In end, In* x ) {
while (begin != end && *begin != x)
++begin;
return begin;
}
It would seem to me that the second implementation is more correct, because it ensures that the type being searched for is the same as the type being referenced by the 'begin' and 'end' iterators. However it doesn't even compile. Is it possible to dereference a template type like that?
Also, in the first implementation, what is the significance of declaring 'x' as 'const X&' rather than just 'X'?
// first implementation
template <class In, class X>
In find ( In begin, In end, const X& x ) {
while (begin != end && *begin != x)
++begin;
return begin;
}This seems to be correct and runs as expected. My question is, why does the following implementation not work?
// second implementation
template <class In>
In find ( In begin, In end, In* x ) {
while (begin != end && *begin != x)
++begin;
return begin;
}
It would seem to me that the second implementation is more correct, because it ensures that the type being searched for is the same as the type being referenced by the 'begin' and 'end' iterators. However it doesn't even compile. Is it possible to dereference a template type like that?
Also, in the first implementation, what is the significance of declaring 'x' as 'const X&' rather than just 'X'?