decltype specifier
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
考察一个实体所声明的类型或查询表达式的返回类型.
原文:
Inspects the declared type of an entity or queries the return type of an expression.
目录 |
[编辑] 语法
decltype ( entity )
|
(1) | (C++11 起) | |||||||
decltype ( expression )
|
(2) | (C++11 起) | |||||||
[编辑] 解释
1)
如果参数是unparenthesised名称的对象/函数,或者是一个成员访问表达式(
object.member
或pointer->member
),然后的decltype指定的声明的类型,该表达式指定的entity.原文:
If the argument is either the unparenthesised name of an object/function, or is a member access expression (
object.member
or pointer->member
), then the decltype specifies the declared type of the entity specified by this expression.2)
如果参数是任何其他类型
T
表达,然后原文:
If the argument is any other expression of type
T
, thena)
b)
如果该值类的expression是“左值”,然后decltype指定
T&
原文:
if the value category of expression is lvalue, then the decltype specifies
T&
c)
否则,,decltype指定
T
需要注意的是,如果一个对象的名称parenthesised,它成为左值表达式,从而decltype(arg)和decltype((arg))往往是不同的类型.
原文:
Note that if the name of an object is parenthesised, it becomes an lvalue expression, thus decltype(arg) and decltype((arg)) are often different types.
decltype
是有用的,当宣布是很难或不可能申报使用标准的符号,如λ-依赖于模板参数的类型或类型的类型.原文:
decltype
is useful when declaring types that are difficult or impossible to declare using standard notation, like lambda-related types or types that depend on template parameters.[编辑] 关键字
[编辑] 示例
#include <iostream> struct A { double x; }; const A* a = new A(); decltype( a->x ) x3; // type of x3 is double (declared type) decltype((a->x)) x4 = x3; // type of x4 is const double& (lvalue expression) template <class T, class 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) f2{f}; // the type of a lambda function is unique and unnamed i = f(2, 2); j = f2(3, 3); std::cout << "i = " << i << ", " << "j = " << j << '\n'; }
输出:
i = 33, j = 66 i = 4, j = 9
[编辑] 另请参阅
(C++11) |
在未经评估的情况下获得了表达式的类型 原文: obtains the type of expression in unevaluated context (函数模板) |