2 ms·
Stroustrop explains his reasoning for the auto keyword here: http://www.stroustrup.com/C++11FAQ.html#auto http://www.stroustrup.com/C++11FAQ.html#auto The u
by chris_wot 11y ago
Stroustrop explains his reasoning for the auto keyword here:
http://www.stroustrup.com/C++11FAQ.html#auto http://www.stroustrup.com/C++11FAQ.html#auto
The use of auto to deduce the type of a variable from its initializer is
obviously most useful when that type is either hard to know exactly or hard to
write. Consider:
template<class T> void printall(const vector<T>& v)
{
for (auto p = v.begin(); p!=v.end(); ++p)
cout << *p << "\n";
}
In C++98, we'd have to write
template<class T> void printall(const vector<T>& v)
{
for (typename vector<T>::const_iterator p = v.begin(); p!=v.end(); ++p)
cout << *p << "\n";
}
When the type of a variable depends critically on template argument it can be
really hard to write code without auto. For example:
template<class T, class U> void multiply(const vector<T>& vt, const vector<U>& vu)
{
// ...
auto tmp = vt[i]*vu[i];
// ...
}