Home C++ Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

C++ 14


Contents

decltype(auto)

The word "auto" lets the compiler figure out the type if it can but it omits the const or reference qualifiers. The "decltype" retains these qualifiers.

File: decl1.cpp
#include <iostream>

using namespace std ;

int main()
{

    const int x = 0;
    auto x1 = x; // int
    x1++ ;
    decltype(auto) x2 = x; // const int
    //Compiler error
    //x2++ ;

    int y = 0;
    int& y1 = y;
    auto y2 = y1; // int
    decltype(auto) y3 = y1; // int&

    int&& z = 0;
    auto z1 = std::move(z); // int
    decltype(auto) z2 = std::move(z); // int&&

}
The above file shows usage of "decltype(auto)" .

    const int x = 0;
	auto x1 = x; // int
	x1++ ;
	decltype(auto) x2 = x; // const int
    //Compiler error
    //x2++ ;

When we do:
 auto x1 = x ;
The type is deduced as int for x1 as const and references are
discarded. However if we do
	decltype(auto) x2 = x; // const int
Then x2 is deduced as const int and we cannot change it's value
later on.