What is the purpose of decltype in C++?
In C++, decltype is used to deduce the type of an expression. Its main purposes include:
- The type of.
auto add(int a, int b) -> decltype(a + b) {
return a + b;
}
- the type of a variable
int a = 5;
decltype(a) b = 10; // b的类型为int
- the type of an expression
int a = 5;
decltype(a + 1) b; // b的类型为int,因为a + 1的类型为int
In general, decltype can deduce the type of an expression, making it easier to infer and define types.