Skip to content

techtrendings.com

Let's explore

Menu
Menu

decltype Keyword C++

Posted on January 10, 2022April 6, 2022 by Avidlearner

The decltype keyword takes an expression as argument, and computes the type of that expression,
as shown here:
int x = 123;
decltype(x) y = 456;


In this example, the compiler deduces the type of y to be int because that is the type of x.
The difference between auto and decltype is that decltype does not strip reference and const
qualifiers. Take the function foo() returning a const reference to a string. Defining f2
using decltype as follows results in f2 being of type const string&, and thus no copy is made.


decltype(foo()) f2 = foo();

It might be worth stressing the difference between auto and decltype: auto works on types, and decltype works on expressions.

Difference between decltype and auto keyword

decltype gives the declared type of the expression that is passed to it. auto does the same thing as template type deduction. So, for example, if you have a function that returns a reference, auto will still be a value (you need auto& to get a reference), but decltype will be exactly the type of the return value.

#include <iostream>
int global=0;
int& func()
{
   return global;
}

int main()
{
    decltype(func()) a = func(); //a is an `int&`
    auto b = func(); //b is an `int`
    b = 2;

    std::cout << "a: " << a << '\n'; //prints "a: 0"
    std::cout << "b: " << b << '\n'; //prints "b: 2"

    std::cout << "---\n";
    decltype(foo()) c = foo(); //c is an `int&`
    c = 10;

    std::cout << "a: " << a << '\n'; //prints "a: 10"
    std::cout << "b: " << b << '\n'; //prints "b: 2"
    std::cout << "c: " << c << '\n'; //prints "c: 10"
 }

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Implement Trie Data Structure in C++- LeetCode
  • How TLS Works
  • C++ – Factory Design Pattern – Creation Design Pattern
  • C++ – Strategy Design Pattern – Behavioral Design Pattern
  • LFU Cache Implementation – LeetCode

Recent Comments

  • automatically like friends photos on instagram on Program to find unpaired element in an Array in C++|Leetcode |techtrendings
  • Twicsy on Program to find unpaired element in an Array in C++|Leetcode |techtrendings

Archives

  • January 2023
  • November 2022
  • August 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022

Categories

  • Algorithm
  • Algorithm
  • C++
  • Design Patterns
  • Multithreading
  • OS Concepts
  • Programming
  • Uncategorized

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Join Our Mailing List for the Latest News and Updates.

© 2023 techtrendings.com | Powered by Superbs Personal Blog theme