首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

decltype specifier

检查实体的声明类型或表达式的类型和值类别。

句法

decltype ( entity )

(1)

(since C++11)

decltype ( expression )

(2)

(since C++11)

解释

1) If the argument is an unparenthesized id-expression naming a structured binding, then decltype yields the referenced type (described in the specification of the structured binding declaration).

(since C++17)

2%29如果参数是无括号的ID-表达式或者一个没有括号的类成员访问表达式,则解密类型生成此表达式命名的实体的类型。如果没有这样的实体,或者如果参数指定了一组重载函数,则程序的格式不正确。

3%29如果参数是任何其他类型的表达式T,和

A%29如果价值范畴表达方式是x值,然后解密收益率T&&

B%29如果表达式的值类别为洛值,然后解密收益率T&

如果表达式的值类别为prvalue,然后解密收益率T...

如果表达式是一个函数调用,该函数调用返回类类型的prvalue或逗号表达式其右操作数是这样一个函数调用,直到C++17%29才会为%28引入一个临时对象。物化从%28到C++17%29的那个prvalue。类类型不必是完全或者有一个可用的破坏者此规则不适用于子表达式:decltype(f(g())),,,g()必须有完整的类型,但是f()不用了。

注意,如果对象的名称为括号,则将其视为普通的lvalue表达式,因此decltype(x)decltype((x))通常是不同的类型。

decltype在声明难以或不可能使用标准表示法声明的类型时,例如与lambda相关的类型或依赖于模板参数的类型时,非常有用。

关键词

decltype...

二次

代码语言:javascript
复制
#include <iostream>
 
struct A { double x; };
const A* a = new A{0};
 
decltype(a->x) y;       // type of y is double (declared type)
decltype((a->x)) z = y; // type of z is const double& (lvalue expression)
 
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u); // return type depends on template parameters
 
int main() 
{
    int i = 33;
    decltype(i) j = i * 2;
 
    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';
 
    auto f = [](int a, int b) -> int
    {
        return a * b;
    };
 
    decltype(f) g = f; // the type of a lambda function is unique and unnamed
    i = f(2, 2);
    j = g(3, 3);
 
    std::cout << "i = " << i << ", "
              << "j = " << j << '\n';
}

二次

产出:

二次

代码语言:javascript
复制
i = 33, j = 66
i = 4, j = 9

二次

另见

auto specifier

specifies a type defined by an expression (C++11)

declval (C++11)

obtains a reference to its argument for use in unevaluated context (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com