What is the purpose of decltype in C++?

In C++, decltype is used to deduce the type of an expression. Its main purposes include:

  1. The type of.
auto add(int a, int b) -> decltype(a + b) {
    return a + b;
}
  1. the type of a variable
int a = 5;
decltype(a) b = 10; // b的类型为int
  1. 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.

bannerAds