[Edit: I really like the ‘range of values’ several commenters proposed. We do need something like that in the standard library, and it may well come in with ranges, but as you can see there are several simple ways to roll your own in the meantime, and some third-party libraries have similar features already.]
Today a reader asked the following question:
So I’ve been reading all I can about c++11/c++14 and beyond when time permits. I like auto, I really do, I believe in it. I have a small problem I’m trying to decide what to do about. So in old legacy code we have things like this:
for (int i = 0; i < someObject.size(); i++) { … }
For some object types size might be unsigned, size_t, int, int64_t etc…
Is there a proper way to handle this generically with auto? The best I could come up with is:
auto mySize = someObject.size();
for (auto i = decltype(mySize){0}; i < mySize; i++) { … }
But I feel dirty for doing it because although it actually is very concise, it’s not newbie friendly to my surrounding coworkers who aren’t as motivated to be on the bleeding edge.
Good question.
First, of course, I’m sure you know the best choice is to use range-for where that’s natural, or failing that consider iterators and begin()/end() where auto naturally gets the iterator types right. Having said that, sometimes you do need an index variable (including for performance) so I’ll assume you’re in that case.
So here’s my off-the-cuff answer:
- If this isn’t in a template, then I think for( auto i = 0; etc. is fine, and if you get a warning about signed/unsigned mismatch just write for(auto i = 0u; etc. This is all I’ve usually needed to do.
- If this is truly generic code in a template, then I suppose for( auto i = 0*mySize; etc. isn’t too bad – it gets the type and it’s not terribly ugly. Disclaimer: I’ve never written this, personally, as I haven’t had a need (yet). And I definitely don’t know that I like it… just throwing it out as an idea.
But that’s an off-the-cuff answer. Dear readers, if you know other/better answers please tell us in the comments.
While we were both at CppCon last month and had cameras around, Brian Overland interviewed me for InformIT. The video just went up a couple of days ago.
Mark Maimone of NASA and Mars Rover fame.
Bjarne taking questions after his talk.
“We’re sold out of A Tour of C++ again… how about this instead?” [photo credit: Artur Laksberg]
[photo credit: Artur Laksberg]
[photo credit: Artur Laksberg]
Walter Brown speaking in one of the six concurrent breakout sessions.
Jon Kalb speaking in one of the other rooms.
Possibly the youngest attendee? [photo credit: Artur Laksberg]
Accessibility and community.
Yup. Modern C++.
View from the CppCon balcony before diving into more evening sessions.
So long, Meydenbauer Center… see you next year! [photo credit: Hyrum Wright]