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"
}