3 ms·
auto can be ambiguous: template<typename Collection> void foo(const Collection &c) { auto x = c.find("foo"); ... } is x an iterator (Collec
by millstone 9y ago
auto can be ambiguous:
template<typename Collection>
void foo(const Collection &c) {
auto x = c.find("foo");
...
}
is x an iterator (Collection is std::map) or a number (Collection is std::string)? Here it is better to write out the iterator type if that's what you mean.
auto can also be downright misleading:
template<typename T>
void foo(std::vector<T> &c) {
auto first = c[0];
...
}
`first` has type T except when T is bool. Gross. Better to write out the type T.
auto can simplify many cases, but please don't take Sutter's "almost always auto" suggestion. Keep your future code readers in mind and be aware of its pitfalls.
- smitherfield 9y ago> is x an iterator (Collection is std::map) or a number (Collection is std::string)? Here it is better to write out the iterator type if that's what you mean. The reader would be able to infer this from context (as is the compiler, so it's still type-safe). > `first` has type T except when T is bool. Gross. Better to write out the type T. That's a preexisting problem with `vector<bool>` much more than it is with `auto`.