×

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the decltype keyword can extract the variable type from another variable. The auto keyword can use all the entities to declare the variable, whereas the decltype keyword is used to extract the variable from the entity. 

What is C++ decltype?

The decltype is a type of operator in C++ that is used to inspect the data type of a particular expression. This feature is available in the C++ 11th version. It is also called C++0x. This specifier performs the expression as an operand. We can also say that the variable defined by using the particular data type can be replaced by the compiler. The information about the data type is provided during the compilation time. Also, info about the decltype can also be provided during the compilation time. The information about the running status of the variable can be supplied by the Typeid type. 

Example-1

#include <iostream>
int main() {
    int j = 55, * k = & j;
    decltype (* k) c = j;
    std::cout<<*k; 


    return 0;
}

Output:

55

Syntax for C++ decltype

We can declare the decltype in C++ as follows.

decltype( expression )

Here, expression is the only parameter of the decltype in C++. Expressions are the sequence of operands and the operator used for computing purpose. 

Guidelines for decltype in C++

There is some guidelines for the use of the decltype operator in C++. The guidelines are as follows:

  1. Suppose the expression parameter has permission to access the member of the class. This class belongs to the type of class entity.  

Example 2:

#include <iostream>
#include <type_traits>


struct A { double x; };
const A* a;


decltype(a->x) y;       
decltype((a->x)) z = y; 


template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u{
    return t + u;
}


const int& getRef(const int* p) { return *p; }
static_assert(std::is_same_v<decltype(getRef), const int&(const int*)>);
auto getRefFwdBad(const int* p) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdBad), int(const int*)>,
    "Just returning auto isn't perfect forwarding.");
decltype(auto) getRefFwdGood(const int* p) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdGood), const int&(const int*)>,
    "Returning decltype(auto) perfectly forwards the return type.");


auto getRefFwdGood1(const int* p) -> decltype(getRef(p)) { return getRef(p); }
static_assert(std::is_same_v<decltype(getRefFwdGood1), const int&(const int*)>,
    "Returning decltype(return expression) also perfectly forwards the return type.");


int main()
{
    int i = 33;
    decltype(i) j = i * 2;


    std::cout << "i and j are the same type? " << std::boolalpha
              << std::is_same_v<decltype(i), decltype(j)> << '\n';


    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';


    auto f = [](int a, int b) -> int
    {
        return a * b;
    };


    decltype(f) g = f; 
    i = f(2, 2);
    j = g(3, 3);


    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';
}

Output:

i and j are the same type? true
i = 33, j = 66
i = 4, j = 9

Example 3:

#include <bits/stdc++.h>
using namespace std;


int function1() { return 29; }
char function2() { return 'h'; }


int main()
{
    
    decltype(function1()) a;
    decltype(function2()) b;


    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;


    return 0;
}

Output:

i
c

Explanation

In the above example, first, we have created two variables of different data types. The first variable is function1, and it is of int type. The second variable is function2 which is of the char type. Then, in the main program, we have used the decltype specifier and assigned the two variables function1 and function2. Then, we have used two cout functions along with the typeid and passed the values a and b to it that returns the result after comparing the data type of a and b and the return type of function1 and function2.

Example 3:

#include <bits/stdc++.h>
using namespace std;


int main()
{
    int p = 10;


   
    decltype(p) h = p + 10;


    cout << typeid(h).name();


    return 0;
}

Output:

i

Explanation

In the above example, we have initialized a variable a of the int type and assigned the value 7. Then, we have used the decltype specifier and passed the variable a to it. Then, we have assigned the a+7 value to g. After that, we have used the cout to print the output.


Related Topics

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.