With this new auto, we can ask the compiler to deduce the type of a declared variable from the expression used to initialize it. This feature is known as type inference, and is found in many functional programming languages. Type inference (or type deduction) introduces some of the advantages of dynamic type systems, without incurring the performance penalty and various other negative side-effects associated with relaxed type safety, such as increased risk of run time failure.
A very basic, and not very useful example could look something like:
int x = 1; auto y = x + 1;The important thing to note here is that auto is a keyword and not a type. This is to say that, unlike in a dynamically typed language, we can’t assign a value of a different type once the variable has been declared. The type of y (int) must be known at compile time, we just leave to the compiler to figure out what it is.
To explore the usefulness of auto, here are some examples:
Iterators
STL iterators are notorious for their verboseness, but with the auto keyword, this code:for (std::vector<std::string>::const_iterator i = v.cbegin(); i != v.cend(); ++i) { // ... }…now becomes simply:
for (auto i = v.cbegin(); i != v.cend(); ++i) { // ... }and similarly:
std::map<int, std::vector<int> >::const_iterator i = m.cbegin(); while (i != m.cend()) { std::pair<int, std::vector<int> > p = *i; // ... ++i; }…can be written:
auto i = m.cbegin(); while (i != m.cend()) { auto p = *i; // ... ++i; }
Lambdas
A lambda in C++0x is a locally defined function. The auto keyword enables us to bind a lambda expression to a variable without explicitly stating its type:auto my_function = [](int x, int y) -> int { return (x * y); };
Conclusion
There is a lot more to be said on this topic, but as we have seen, the auto keyword can improve readability of code and be of great use when working with complex template types.More information is available on MSDN:
http://msdn.microsoft.com/en-us/library/dd293667.aspx
0 comments:
Post a Comment