decltype c++11

来源:互联网 发布:sql数据库管理网页版 编辑:程序博客网 时间:2024/06/05 14:54
    Sometimes we want to define a variable with a type that the compiler deduces from a expression but do not want to use that expression to initialize the variable. For such cases, the new standard introduced a second type specifier, decltype which return the type of its operand. The compiler analyzes the expression to determine its type but does not evaluate the expression:
    decltype(f()) sum = x;
    Here, the compiler does not call f, but it use the type that such a call would return as the type for sum. That is, the compiler gives sum the same type as the type that would be returned if we were to call f.
    The way decltype handles top-level const and references differs subtly from the way auto does. When the expression to which we apply decltype is a variable, decltype returns the type of that variable, including top-level const and references:
    const int ci = 0, &cj = ci;
    decltype(ci) x = 0;    // x has type const int
    decltype(cj) y = 0;    // y has const int & and is bound to x
    decltype(cj) z;        // error: z is a reference and must be initialized
Because cj is a reference, decltype(cj) is a reference type. Like any other reference, z must be initialized.
    It is worth noting that decltype is the only context in which a variable defined as a reference is not treated as a synonym for the object to which it refers.
0 0
原创粉丝点击