Home > Articles > Programming > C/C++

A Magic Spell: Using auto and decltype in C++11 to Declare Objects Without Spelling Out Their Types

C++11 weaves its magic to help you eliminate keystrokes and simplify your code, safely transferring some of your workload to the compiler. With two new C++11 features, you can omit the type of an object from its declaration, and the compiler ingeniously deduces the missing type by examining the initializer used in the declaration. Danny Kalev reveals the secret behind the curtain.
Like this article? We recommend

One of the principles of the C++ design philosophy is that whenever there's a choice between inconveniencing the programmer and inconveniencing the compiler, the latter should be preferred. Two new C++11 features, auto and decltype, take this design philosophy one step further, letting you omit the type of an object from its declaration. As if by magic, the compiler deduces the missing type by examining the initializer used in the declaration. A similar mechanism for capturing the type of an expression is provided by a new C++11 operator called decltype. Together, auto and decltype eliminate unnecessary keystrokes and simplify your code without compromising type-safety, code readability, and performance. In the following sections, I'll show how to use these new C++ features.

Automating Type Deduction

To estimate the merits of auto, consider the following C++03 declarations:

int page_no=0;
double coeff=3.6666667;
const static char error_message[]="unit malfunction";
bool dirty=false;

These four declarations have two things in common:

  • They include an explicit initializer.
  • They spell out the object's type explicitly.

C++ users noticed a long time ago that spelling out the type in such declarations is redundant, because the initializers already convey the type implicitly. For example, the literal 0 is int, 3.6666667 is double, and false can only be a value of type bool. Furthermore, in some cases, even C lets you omit certain type properties (such as the size of an array) when the compiler is able to retrieve those properties from the initializer, as shown in the declaration of error_message above. If the compiler can retrieve the type information from the initializers, why not free the programmer from this burden completely?

At first, it was believed that automatic type deduction was just a minor convenience. However, contemporary C++ apps make extensive use of Standard Library components such as containers and iterators. In such apps, forcing the programmer to spell out the type of an iterator in every for loop, for example, isn't just a nuisance—it compromises code readability. Consider:

for (std::vector<Widget>::iterator iter = vw.begin(); iter<vw.end(); iter++)
{
iter->print_name();
}

Omitting the type from the declaration of iter improves the for loop's readability:

for (auto iter = vw.begin(); iter<vw.end(); iter++)
{
iter->print_name();
}

auto in Action

The new C++11 keyword auto lets you omit the type of an object being declared, so long as the declaration includes an initializer.

Using auto, you can rewrite the four previous declarations like this:

auto page_no=0;
auto coeff=3.6666667;
auto error_message="unit malfunction"; //notice that the [] were omitted too!
auto dirty=false;
auto str=std::string("hello");

Let's examine each of these declarations more carefully to understand how the compiler deduces the correct type of each object:

  • page_no is easy—the literal 0, which is polymorphic in C++ (it could mean a null pointer, among the rest), is taken to be int by default.
  • coeff is similar: A literal number with a decimal point is taken to be a double.
  • error_message is a more interesting case. Even without brackets, the compiler knows that this is a char array because text enclosed in double quotes (″″) implies a static const char array. The compiler counts how many characters are enclosed between the pair of double quotes (including a null terminator), and it uses that information to assign the size of the array.
  • In a similar vein, an auto declaration of an int array looks like this:

    auto a={5,8,10};
  • Finally, the initializer of dirty is the keyword false, which is a bool literal. Therefore, the compiler assumes that dirty is of type bool.

CV Qualification and Arrays

All well and good so far. However, the former declarations didn't include const or volatile qualifiers (cv qualifiers). What if you want to declare a cv-qualified object using auto? Generally speaking, initializers cannot encode that information. The compiler can't tell whether 3.6666667 is of type double, const double, const volatile double, or volatile double. By default, literals (except quoted strings) are assumed not to be cv-qualified. Therefore, if you want to declare a cv-qualified object using auto, you should state the cv-qualification explicitly in the declaration:

const auto PAGE_SIZE=512; //const int
auto const volatile coeff=3.6666667; //const volatile double
const volatile auto coeffarr={3.6666667, 2.65, 1.3333}; //const volatile double[]

My compiler, which isn't fully-conformant with the C++11 standard yet, chokes on that last declaration. Expect similar grunts and moans from your compiler in the near future until vendors have fully implemented the new features of C++11.

On that note, two tricks could help here. First, replace the ={} notation for arrays with the new C++11 style brace-enclosed initializer list, which doesn't have the equal (=) sign. In other words, try to rewrite the last declaration like this:

const volatile auto coeff_arr {3.6666667, 2.65, 1.3333}; //C++11 brace-init notation, no=

Another trick that could help in some cases is #including the new C++11 header file <initializer_list> in your program:

auto c='A'; //char
#include <initializer_list> //needed for brace-enclosed initializer lists
auto a={5,8,10}; //int[3]

According to the C++11 standard, the compiler must #include <initializer_list> implicitly in every translation unit in which that header is required, so essentially you're not supposed to write any #include <initializer_list> directives in your code. (Initializer lists will be the topic of a separate article.) However, this requirement was added to the C++11 standard recently. Therefore, some implementations don't follow the rules yet.

Derived Types

As far as int, char, double, and other fundamental types are concerned, auto declarations seem straightforward. However, what about more complex types such as pointers and pointers to functions? Remember this rule: So long as the initializer itself is an object of the desired type, you can use it in an auto declaration to declare another object with the same type. Put differently, you're not confined to using literals as initializers. The following example uses an existing pointer to Widget to auto-declare another pointer to Widget, and an array thereof:

Widget* pw= new Widget;
auto pw2=pw; //Widget*
auto pwarr {pw2, new Widget, pw}; //array of three Widget*

Following the same pattern, here's an auto declaration of a pointer to a function that takes bool and returns int:

int func(bool);
auto fptr=func; //OK, type is int(*)(bool)

Finally, if you want to declare an array of pointers to functions of this type, use the following initializer:

auto fptr{func, func}; //OK, type is int(*[2])(bool)

Capturing the Type of an Expression Using decltype

The new C++11 operator decltype is similar to auto in the sense that it deduces the type of an expression without any further assistance from the programmer. You can then use the "captured" type to declare another object with the same type, create a typedef, or have the compiler calculate a function's return type for you.

Suppose you want to capture the iterator type that a vector::begin() call returns. Use decltype like this:

vector<Widget> vw;
typedef decltype(vw.begin()) MYIT;

MYIT is a typedef name synonymous with the return type of vw.begin(). decltype is chiefly useful in generic programming for capturing the types of complex declarations, particularly nested templates. In a way, decltype complements auto by letting you "uncover" the type of an object that was declared using auto. Consider:

auto iarr {0,1}; //int[2]
//uncover the type of iarr and use it to declare a new typedef
typedef decltype(iarr)  intarray;
intarray x;
x[0]=3;
x[1]=2;

Any valid C++ expression makes a perfect argument for decltype. Here are a few examples:

typedef decltype(5) MYINT;  //using a literal
float x;
typedef decltype(x) MYFLOAT; //using a variable
typedef decltype (std::string()) MYSTR; //using a temporary
typedef decltype(2.5*0.666) MYDOUBLE; //math expressions will also work

You can even use a comma-separated expression as a decltype argument. Recall that the type of a comma-separated expression is always the type of the rightmost sub-expression:

typedef decltype (5, 'a') MYCHAR;
MYCHAR greeting[]="hello";

New Function Declaration Syntax

C++11 also introduced a new notation for function declarations that takes advantage of auto and decltype. Here's an example of a new-style function declaration:

auto func(int x)-> double; //C++11 style function declaration

func()'s return type is double. Generally speaking, the return type of auto functions is called a trailing return type. A trailing return type is preceded by an arrow sign (->)after the parameter list. The arrow sign is made up of two characters: a hyphen (-) and a right angle bracket (>). You probably recognize the -> sign—that's the same arrow sign you use for accessing a member through a pointer to an object, as in the following example:

pobj->func();

Combining auto and decltype enables the compiler to generate a function's return type automatically from an expression or a value. For example, you can use a parameter's name to derive the function's return type:

auto g(double d)-> decltype(d); //return type is double

Similarly, template functions can generate their return types automatically, like this:

template <class T>
auto get_end(vector<T>& v) {return v.end())
 ->decltype(v.end()); //return type is vector<T>::iterator

vector<Widget> vw;
get_end(vw); //returns vector<Widget>::iterator

template <class T>

auto get_end(const vector<T>& v) {return v.end())
 ->decltype(v.end());

const vector<Widget> cvw;
get_end(cvw); //returns vector<Widget>::const_iterator

In Conclusion

C++ programmers migrating to C++11 often say that auto and decltype are the features they like most. And yet, auto and decltype aren't just a matter of convenience; they prove useful in the design of generic code, where the automatic deduction of a return type, iterator, and so on in accordance with every template specialization is essential. It's no wonder that many other programming languages have started to imitate the C++11 auto.

Danny Kalev is a certified system analyst and software engineer specializing in C, C++ Objective-C and other programming languages. He was a member of the C++ standards committee until 2000 and has since been involved informally in the C++ standardization process. Danny is the author of ANSI/ISO Professional Programmer's Handbook (1999) and The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++ (2005). He was also the Informit C++ Reference Guide. Danny earned an M.A. in linguistics, graduating summa cum laude, and is now pursuing his Ph.D. in applied linguistics.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020