C++ decltype Keyword
The decltype
keyword in C++ is used to deduce the type of an expression at compile-time. Introduced in C++11, it allows you to determine the exact type of a variable, expression, or function result without explicitly knowing its type. This feature is particularly useful in template programming and when dealing with complex expressions or return types.
Syntax
</>
Copy
decltype(expression) variable_name;
- decltype
- The keyword used to deduce the type of the provided expression.
- expression
- An expression whose type is to be deduced, such as a variable, function, or operation.
- variable_name
- The name of the variable to be declared using the deduced type.
Examples
Example 1: Deducing Variable Type
This example demonstrates how to use decltype
to deduce the type of a variable from another variable.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 10;
decltype(a) b = 20; // 'b' has the same type as 'a'
cout << "a: " << a << ", b: " << b << endl;
return 0;
}
Output:
a: 10, b: 20
Explanation:
- The type of
a
isint
. decltype(a)
deduces the type ofa
and uses it to declareb
.- Both
a
andb
are of typeint
, and their values are printed accordingly.
Example 2: Deducing Function Return Type
This example demonstrates using decltype
to deduce the return type of a function.
</>
Copy
#include <iostream>
using namespace std;
int add(int x, int y) {
return x + y;
}
int main() {
decltype(add(0, 0)) result = add(5, 3); // Deduces the return type of 'add'
cout << "Result: " << result << endl;
return 0;
}
Output:
Result: 8
Explanation:
- The function
add
returns anint
, which is deduced bydecltype(add(0, 0))
. - The variable
result
is declared with the deduced typeint
. - The result of the function call
add(5, 3)
is stored inresult
and printed.
Example 3: Using decltype
with Expressions
This example demonstrates using decltype
to deduce the type of an expression.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int x = 10;
float y = 5.5;
decltype(x + y) z = x + y; // Deduces the type of the expression 'x + y'
cout << "z: " << z << endl;
return 0;
}
Output:
z: 15.5
Explanation:
- The expression
x + y
involves anint
and afloat
, so the result is afloat
. decltype(x + y)
deduces the type of the expression, which isfloat
.- The variable
z
is declared with typefloat
and stores the result ofx + y
.
Key Points about decltype
Keyword
- The
decltype
keyword deduces the type of an expression at compile-time. - It is particularly useful in template programming and situations where the type is determined by complex expressions.
decltype
can deduce the type of variables, expressions, and function return values.- Unlike
auto
, which deduces a type based on initialization,decltype
queries the type of an expression without requiring initialization.