decltype
decltype
is a keyword in C++ that is used to query the type of an expression at compile time. It allows you to deduce the type of a variable or an expression without explicitly specifying the type. This is particularly useful when working with templates or when you want to avoid redundant type declarations.
#include <iostream>
int main() {
int x = 5;
double y = 3.14;
// Use decltype to get the type of x
decltype(x) a; // a is of type int
a = 10;
// Use decltype to get the type of y
decltype(y) b = y * 2; // b is of type double
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
return 0;
}
decltype(x)
deduces the type of x
, which is int
, so a
is declared as an int
.decltype(y)
deduces the type of y
, which is double
, so b
is declared as a double
.Use with function return types
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
int x = 10;
int y = 20;
decltype(add(x, y)) result; // result is of type int
result = add(x, y);
std::cout << "result: " << result << std::endl;
return 0;
}
#include <iostream>
template<typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a + b) {
return a + b;
}
int main() {
int x = 10;
double y = 5.5;
auto result = add(x, y); // result is of type double
std::cout << "result: " << result << std::endl;
return 0;
}
In the template function add, decltype(a + b)
is used to deduce the return type based on the types of a
and b
. In this case, since one of the operands is double, the result is double
.
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
// Capture the type of the first element in the vector
decltype(vec[0]) first_element = vec[0];
first_element = 10;
std::cout << "first_element: " << first_element << std::endl;
return 0;
}
decltype(vec[0])
deduces the type of the first element of the vector, which is int&
(a reference to int
). This allows you to create variables with the exact type of the elements in a container.
decltype
is a powerful tool for deducing types in C++.