Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decltype vs auto

As I understand it, both decltype and auto will attempt to figure out what the type of something is.

If we define:

int foo () {     return 34; } 

Then both declarations are legal:

auto x = foo(); cout << x << endl;  decltype(foo()) y = 13; cout << y << endl; 

Could you please tell me what the main difference between decltype and auto is?

like image 269
James Leonard Avatar asked Aug 23 '12 02:08

James Leonard


People also ask

What does decltype stand for?

Decltype keyword in C++ Decltype stands for declared type of an entity or the type of an expression. It lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. SYNTAX : decltype( expression )

What is the difference between auto and decltype?

auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.

Is it good to use auto in C++?

While in the former case, the usage of auto seems very good and doesn't reduce readability, and therefore, can be used extensively, but in the latter case, it reduces readabilty and hence shouldn't be used.

What is decltype used for?

In the C++ programming language, decltype is a keyword used to query the type of an expression. Introduced in C++11, its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.


1 Answers

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{}; int& foo() {    return global; }  int main() {     decltype(foo()) a = foo(); //a is an `int&`     auto b = foo(); //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"  } 

Also see David Rodríguez's answer about the places in which only one of auto or decltype are possible.

like image 153
Mankarse Avatar answered Sep 25 '22 14:09

Mankarse