Sometimes you want a new variable to have the exact same type as an already existing variable or expression. To let the C++ compiler figure out that type, we use decltype.
Use the decltype keyword by placing an expression inside its parentheses. The C++ compiler analyzes the type of that expression and uses it as the type of the new variable.
#include <iostream>
int main()
{
int number{42};
// Derive the type from this expression without evaluating it
decltype(number) copy{100};
std::cout << number << ' '
<< copy
<< '\n';
}
Here, decltype(number) refers to the type of the variable number, so it produces int. The new variable copy is therefore also an int, and you do not need to write the type yourself.
The C++ compiler treats each expression inside decltype separately. A new variable receives the same type as the expression given to decltype.
#include <iostream>
int main()
{
int x{10};
double y{3.14};
char letter{'A'};
decltype(x) a{20};
decltype(y) b{2.71};
decltype(letter) c{'B'};
std::cout << a << ' '
<< b << ' '
<< c
// Use the newline escape sequence inside this literal
<< '\n';
}
It is useful when a type is long and when we want to ensure that two variables have matching types.
We can also place a more complex expression, such as m + n, inside decltype.
#include <iostream>
int main()
{
int m{5};
int n{7};
decltype(m + n) new_sum{m + n};
std::cout << "Result is "
<< new_sum
// Use the newline escape sequence inside this literal
<< '\n';
}
The compiler sees that the result of m + n has type int, so it gives new_sum that same type. The compiler analyzes only the type of the expression inside decltype. It does not evaluate that expression as part of decltype.
#include <iostream>
int main()
{
int score{85};
decltype(score) high_score{100};
decltype(score) total{score + high_score};
std::cout << "Score: "
<< score
<< '\n';
std::cout << "High score: "
<< high_score
<< '\n';
std::cout << "Total: "
<< total
<< '\n';
}
With this, your intention to make high_score the same type as score becomes obvious and clear. If the type of score changes, the related variables declared with decltype(score) will change automatically as well.
0 comments
No comments yet. Be the first.