What is the relation between auto and decltype in C++?

C++ProgrammingObject Oriented Programming

Auto and decltype serve different purposes so they don't map one-to-one. auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it. The value returned by decltype can directly be used to define another variable.

auto follows the rules of template parameter deduction. You can read more about these rule at http://en.cppreference.com/w/cpp/language/template_argument_deduction

While decltype has rules it should follow defined in the standard. Here is an excerpt from the standard with these rules:

Similarly to the sizeof operator, the operand of decltype is unevaluated. Informally, the type returned by decltype(e) is deduced as follows −

  • If the expression e refers to a variable in local or namespace scope, a static member variable or a function parameter, then the result is that variable's or parameter's declared type
  • If e is a function call or an overloaded operator invocation, decltype(e) denotes the declared return type of that function
  • Otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e; if e is an rvalue, the result is T

These semantics were designed to fulfill the needs of generic library writers, while at the same time being intuitive for novice programmers because the return type of decltype always matches the type of the object or function exactly as declared in the source code. More formally, Rule 1 applies to unparenthesized id-expressions and class member access expressions. For function calls, the deduced type is the return type of the statically chosen function, as determined by the rules for overload resolution. 

Example

Example using auto and decltype,

#include<iostream>
#include<vector>

using namespace std;

int main() {
    // Using auto for type deduction
    vector<int> arr(10);
    for(auto it = arr.begin(); it != arr.end(); it ++) {
        cin >> *it;
    }

    // Using decltype for type deduction
    vector<int> arr(10);
    for (decltype(arr.begin()) it = arr.begin(); it != arr.end(); it++) {
        cin >> *it;
    }
    return 0;
}

Note that The type denoted by decltype can be different from the type deduced by auto. You can read more about these subtle differences in this 12-page explanation of type deduction in C++ − http://thbecker.net/articles/auto_and_decltype/section_01.html

raja
Published on 16-Feb-2018 06:45:54
Advertisements