Reputation: 39
What has happened to this statement:
auto iter = first;
Why iter++
can work well, as we all know, first
is const&
,
template<typename iteratorT, typename valueT>
iteratorT find(const iteratorT& first, const iteratorT& last,const valueT& value)
{
auto iter = first;
while(iter != last && *iter != value) iter++;
return iter;
}
Why?
Upvotes: 1
Views: 164
Reputation: 50550
That's how type deduction works when using auto
, in the example you are getting a copy of first
and that copy has type iteratorT
.
You can use instead:
const iteratorT &iter = first
const auto &iter = first
(or just auto &
)decltype(first) iter = first
decltype(auto) iter = first
All of them if you want iter
to be a const reference, of course.
Thanks to @songyuanyao and @LogicStuff for theirs suggestions in the comments.
Consider also the following example that reproduces your issue in a cleaner way:
#include <type_traits>
int main() {
int i = 42;
const int & j = i;
auto k = j;
static_assert(std::is_same<decltype(k), int>::value, "!");
static_assert(not std::is_same<decltype(k), const int &>::value, "!");
}
Upvotes: 5