C++0x Automates Type Deduction with auto

C++0x Automates Type Deduction with auto

nother C++0x feature is going to simplify the way you write C++ code. Instead of tediously writing the type of a variable when you declare it, a C++0x compiler will deduce the variable’s type automatically simply by looking at its initializer?if you ask it to. The following sections will demonstrate how to use this feature.

Declaring the type of certain variables (for example, iterators) leads to code clutter and maintenance difficulties.

Use the revamped auto keyword to let the compiler automatically deduce a variable’s type from its initializer.

Presenting the Problem
Suppose you have a vector of strings:

#include #include using namespace std;vector 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::iterator it=vs.begin();    it

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 intauto y=2.0; //y is doubleauto z=10ULL; //unsigned long longauto 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

It's as simple as that!

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

Pointers and References
For simple type declarations, the use of auto is rather intuitive. However, what happens when the initializer is a reference?

int& myfunc();int yourfunc();auto j=myfunc(); //int& or int?

The authors decided to apply the same rules of template type deduction. The type of j is therefore int, not int&. To create an auto reference variable, you need to use this form:

auto& j=myfunc(); // int&

Similarly, to add cv-qualification to the variable, use this syntax:

const auto& ci=yourfunc(); //const int&

If the initializer is a pointer, the compiler will deduce the pointer's type and assign it to the auto variable. You can omit the * in an auto declaration if the initializer is a pointer:

int n;auto pi=&n;//pi is int*auto* pi2=&n; //also int*auto* p = new Myclass; //Myclass*auto p2 = new Myclass //Myclass *

Notice however that the compiler will deduce the type based on the entire initializer expression. In the following example, the type of q is Myclass, not Myclass*:

auto q= *new Myclass;  

Similarly, auto can be used in a new expression:

new auto('s');  

The type of auto('s') is char. Therefore, the type of the expression new auto('s') is char *. Here's another example:

new auto(1000LL); //new long long*. const auto p= new auto(1000LL); //p is const long long*

Multi-Variable Declarations
Originally, the auto proposal allowed only one variable to be declared in every auto statement. This restriction was later removed, so now you can declare multiple variables in a single auto statement:

auto a=6.8, *pa = &a; //a is double, pa is double*

According to the latest version of the auto proposal, the status of array declarations isn't clear. At the time of writing, the following isn't allowed:

auto arr[]={1,2,3,4};//error, arrays aren't allowed

Similarly, the status of this borderline case is also being debated:

int x[4];auto y = x; // int*? 

Ready to Use
The new syntax for automatic type deduction simplifies your code by eliminating unwieldy type names from declarations and expressions. Several issues with auto still need to be resolved, though: array declarations, typedefs, and pointers to functions. At present, some implementations already support auto, Comeau for instance, so you don't have to wait for the ratification of the C++0x standard to start using this feature.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist