×

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

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 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.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.