Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

C++0x Automates Type Deduction with auto-2 : Page 2


advertisement
Presenting the Problem
Suppose you have a vector of strings:

#include <vector> #include <string> using namespace std; vector<string> vs; vs.push_back("myname"); vs.push_back("yourname");

You want to print every string in the vector. In a C++98 style for-loop, you'd declare an iterator inside a for loop and use that iterator to traverse the vector:

for(vector<string>::iterator it=vs.begin(); it<vs.end(); ++it) { cout<<*it<<endl; }

Most of the code in this loop consists of the unwieldy type of the iterator it. For-loops of this kind are very common in code that uses Standard Library containers, and frankly, who doesn't use containers these days? And yet, this coding style leads to maintenance problems. For example, if you replace vector with another standard container, you will have to chase every iterator declaration and change it accordingly.



The code above would be simpler, more readable, and easier to maintain if the compiler assigned the correct type for the iterator it according to its initializer.

A C++09 proposal for deducing the type of a variable form its initializer expression makes this possible. The archaic auto keyword, which has virtually no use in C++98, is now being resurrected, albeit with completely different semantics.

Author's Note: At their February meeting, the C++ standards committee decided to drop the auto storage-class specifier from the language. This will eliminate ambiguities that might arise when the storage-class auto conflicts with the new semantics of the same keyword. Henceforth, objects allocated on the stack will be called "objects with automatic storage type", or "automatic objects" for short.

To enable the compiler's automatic deduction of a variable's type, omit the type from the declaration and replace it with the keyword auto. The compiler will detect the type of the initializer and assign that type to the variable being declared:

std::string myfunc(); auto x=1; //x is int because the type of 1 is int auto y=2.0; //y is double auto z=10ULL; //unsigned long long auto s=myfunc; //s is std::string

Using the auto facility, the for-loop above can now be rewritten like this:

for (auto it=vs.begin(); it<vs.end(); ++it){ cout<<*it<<endl; }

It's as simple as that!

To deduce the type of it, the compiler has to look at the type of vector<string>::begin(). The compiler knows that vector<string>::begin() returns vector<string>::iterator and assigns that type to the iterator it.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap