What Is Decltype (auto) In Modern C++ And How To Use It?
The auto keyword arrives with the new features of the C++11 and the standards above. In C++14, there is a new decltype that is used with auto keyword. In modern C++, the decltype(auto) type-specifier deduces return types while keeping their references and cv-qualifiers, while auto does not. In this post, we explain what decltype (auto) is in modern C++ and how to use it. What is auto in modern C++? The auto keyword is used to define variable types automatically, it is a placeholder type specifier (an auto-typed variable), or it can be used in a function declaration, or a structured binding declaration. If you want to learn more about auto keyword, here it is, What is decltype in modern C++? The decltype keyword and operator represents the type of a given entity or expression. This feature is one of the C++11 features added to compilers (including BCC32 and other CLANG compilers). In a way you are saying “I am declaring this variable to be the same type as this other variable“. Here are more details about how you can use it, How to use decltype (auto) in modern C++? In C++14, there is a new decltype feature that allows you to use with the auto keyword. In C++14 and standards above, the decltype(auto) type-specifier deduces return types while keeping their references and cv-qualifiers, while auto does not. Since C++14, here is the syntax, type_constraint (optional) decltype ( auto ) In this syntax, the type is decltype(expr) and expr can be an initializer or a return statement. Here is a simple example how we can use it, decltype(auto) x = i; Are there some simple examples about decltype (auto) in modern C++? Here are some simple examples that shows difference between auto and decltype(auto), In C++14 and above, we can use decltype(auto) with const int values as below, const int x = 4096; auto xa = x; // xa : int decltype(auto) xb = x; // xb : const int In C++14 and above, we can use decltype(auto) with int& values as below, int y = 2048; int& y0 = y; // y_ : int auto ya = y0; // yc2 : int decltype(auto) yb = y0; // yb : int& In C++14 and above, we can use decltype(auto) with int values as below, int&& z = 1024; auto zm = std::move(z); // zm : int decltype(auto) zm2 = std::move(z); // zm2 : int&& In C++11 and above, we can use auto for return types, auto myf(const int& i) { return i; // auto return type : int } In C++14 and above, we can use decltype(auto) for return types, decltype(auto) myf2(const int& i) { return i; // decltype(auto) return type : const int& } Is there a full example about decltype (auto) in modern C++? Here is a full example that shows how you can use auto and decltype(auto) in different int types. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 #include auto myf(const int& i) { return i; // auto […]
