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?
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 )
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With