笔记:C++ decltype类型说明符(尾置返回类型使用)

转自https://blog.csdn.net/yhl_leo/article/details/50865552

1 基本语法

decltype 类型说明符生成指定表达式的类型。在此过程中,编译器分析表达式并得到它的类型,却不实际计算表达式的值。

语法为:

decltype( expression )

笔记:expression可以是变量,也可以是函数;decltype作用是获得expression的类型;如果声明是设定函数(返回值类型)或变量的类型,那么,decltype是声明的反向操作,获得这些函数或变量的类型;初步认知decltype 和 auto有点类似,但肯定也有所不同。

编译器使用下列规则来确定expression 参数的类型。

  • 如果 expression 参数是标识符类成员访问,则 decltype(expression) 是 expression 命名的实体的类型。如果不存在此类实体或 expression 参数命名一组重载函数,则编译器将生成错误消息。
  • 如果 expression 参数是对一个函数或一个重载运算符函数的调用,则 decltype(expression) 是函数的返回类型。将忽略重载运算符两边的括号。
  • 如果 expression 参数是右值,则 decltype(expression) 是 expression类型。如果 expression参数是左值,则 decltype(expression) 是对 左值引用 类型的expression。

笔记:左值 和 右值?等号的左边类型,即左值;如果返回左值,说明可以被赋值;右值就不用说了

示例代码:

int var;    // 声明一个变量
const int&& fx();   // 声明一个函数
struct A { double x; } const A* a = new A();			// 声明一个结构体 并创建一个结构体对象		
语句类型注释
decltype(fx());const int &&对左值引用的const int
decltype(var);int变量 var 的类型
decltype(a->x);double成员访问的类型
decltype((a->x));const double&内部括号导致语句作为表达式,而不是成员访问计算。由于a声明为 const指针,因此类型是对const double的引用。

笔记:注意 decltype(a->x);,没有内部括号时,只获取x的类型;当decltype((a->x)); 多了一层内部括号时,a->x作为一个整体,除了关注x意外,还需要关注a的声明;因此decltype则获取的是类型需要包含 a的声明(const指针),x 的double类型,因此为const double&。

2 decltype和引用

如果decltype使用的表达式不是一个变量(比如:函数),则decltype返回表达式结果对应的类型。但是有些时候,一些表达式向decltype 返回一个引用类型。一般来说,当这种情形发生时,意味着该表达式的结果对象能作为一条赋值语句的左值

// decltype的结果可以是引用类型
int i = 42, *p = &i, &r = i;

decltype(r) a;		// Error 因为r是引用,a是int&, 因此必须初始化

decltype(r + 0) b; 	// OK, 加法的结果是int,因此b是一个(未初始化)的int 

decltype(*p) c; 	// Error, p是指针类型,*p解引用操作,c是int&, 必须初始化

因为r是一个引用,因此decltype®的结果是引用类型,如果想让结果类型是r所指的类型,可以把r作为表达式的一部分,如r+0,显然这个表达式的结果将是一个具体的值而非一个引用。

另一方面,如果表达式的内容是解引用操作,则decltype将得到引用类型。正如我们所熟悉的那样,解引用指针可以得到指针所指对象,而且还能给这个对象赋值,因此,decltype(*p)的结果类型是int&而非int。

3 decltype和auto

  • 处理顶层const和引用的方式不同(参考阅读:C++ auto类型说明符)

如果decltype使用的表达式是一个变量,则decltype返回该变量的类型(包括顶层const引用在内):

const int ci = 0, &cj = ci;
decltype(ci) x = 0; 	// x的类型是const int 
decltype(cj) y = x; 	// y的类型是const int&,y绑定到变量x 
decltype(cj) z; 		// Error, z是一个引用,必须初始化
  • decltype的结果类型与表达式形式密切相关

对于decltype所用的引用来说,如果变量名加上了一对括号,则得到的类型与不加括号时会有所不同
如果decltype使用的是一个不加括号的变量,则得到的结果就是该变量的类型
如果给变量加上了一层或多层括号,编译器就会把它当成是一个表达式

int i = 42;
decltype((i)) d; // Error, d是int&, 必须初始化
decltype(i) e;   // OK, e是一个未初始化的int

模板函数的返回类型

  • 在 C++11 中,可以结合使用尾随返回类型上的 decltype 类型说明符和 auto 关键字来声明其返回类型依赖于其模板参数类型模板函数
  • 在 C++14 中,可以使用不带尾随返回类型的 decltype(auto) 来声明其返回类型取决于其模板参数类型的模板函数。
    例如,定义一个求和模板函数:
//C++11
 template<typename T, typename U>
auto myFunc(T&& t, U&& u) -> decltype (forward<T>(t) + forward<U>(u)) 
{ return forward<T>(t) + forward<U>(u); }; 

//C++14 
template<typename T, typename U> 
decltype(auto) myFunc(T&& t, U&& u) 
{ return forward<T>(t) + forward<U>(u); }; 

(forward:如果参数是右值或右值引用,则有条件地将其参数强制转换为右值引用。)

笔记:熟练模板的用法?

一段源码:

#include <iostream>
#include <string>
#include <utility>
#include <iomanip>
 
using namespace std; 

// 模板函数
template<typename T1, typename T2> auto Plus(T1&& t1, T2&& t2) -> decltype(forward<T1>(t1) + forward<T2>(t2)) 
{ 
	return forward<T1>(t1) + forward<T2>(t2);
} 
	 
class X 
{ 
	friend X operator+(const X& x1, const X& x2) 
	{ 
		return X(x1.m_data + x2.m_data); 
	} 

public: 
	X(int data) : m_data(data) {}
	int Dump() const { return m_data;}
	 
private: 
	int m_data; 
}; 


int main() 
{ 
	// Integer 
	int i = 4; 
	cout << "Plus(i, 9) = " << Plus(i, 9) << endl; 

	// Floating point 
	float dx = 4.0; 
	float dy = 9.5; 
	cout << setprecision(3) << "Plus(dx, dy) = " << Plus(dx, dy) << endl; 

	// String 
	string hello = "Hello, "; 
	string world = "world!"; 
	cout << Plus(hello, world) << endl; 

	// Custom type 
	X x1(20); 
	X x2(22); 
	X x3 = Plus(x1, x2); 
	cout << "x3.Dump() = " << x3.Dump() << endl; 
}

运行结果为:

Plus(i, 9) = 13
Plus(dx, dy) = 13.5
Hello, world!
x3.Dump() = 42

auto 与 decltype 理解

auto的占位符可能会出现在下列的情况中使用:

  • 在变量的类型说明符中:auto x = expr; 。 从初始化程序推导类型。
    例如,给定 const auto&i = expr ;,

    • 如果编译了函数调用f(expr),则i 的类型恰好是模板函数template void f(const U&u)中参数u的类型。
      因此,根据初始化程序,可以将auto &&推导出为左值引用或右值引用,该值在基于范围的for循环中使用。
    • 如果占位符类型说明符为**decltype(auto)**或类型约束decltype(auto),推导出的类型是decltype(expr),其中expr是初始化。
    • 如果使用占位符类型说明符声明多个变量,则推导的类型必须匹配。
      例如,声明auto i = 0,d = 0.0; 编译时显示格式错误,而声明auto i = 0,* p =&i; 编译时则格式正确,并且将auto推导为int。
  • 在新表达式的type-id中: 从初始化程序推导类型。 对于新的T init(其中T包含占位符类型,init是带括号的初始化程序或用括号括起来的初始化程序列表),就像在发明声明T x init;中对变量x一样,推导出T的类型。

  • (自C ++ 14起)函数或lambda表达式的返回类型:auto&f();。 返回类型是从其未丢弃(自C ++ 17起)return语句的操作数推导出的。

  • (从C ++ 17开始)在非类型模板参数的参数声明中:template struct A;。 它的类型是从相应的参数推导出来的。

  • 此外,auto和type-constraint auto(自C ++ 20起)可以出现在:

    • Lambda表达式的参数声明:[](auto &&){}。 这样的lambda表达式是通用lambda。 (自C ++ 14起);
    • (自C ++ 20起)函数参数声明:void f(auto);。 函数声明引入了一个缩写的函数模板。
  • 如果存在类型约束,则让T为为占位符推导的类型,T必须满足立即声明的类型约束的约束。 那是 :

    • 如果类型约束是C o n c e p t < A 1 , . . . , A n > Concept <A_1,…,A_n>Concept<A 1,…,An>
      则约束表达式C o n c e p t < T , A 1 , . . . , A n > Concept <T,A_1,…,A_n>Concept<T,A 1,…,A n>必须有效并返true;;
    • 否则(类型约束是不带参数列表的Concept),约束表达式Concept 必须有效并返回true。.

在C ++ 11之前,auto具有存储持续时间说明符的语义。

在一个声明中混合自动变量和函数,如auto f()-> int,i = 0; 是不被允许的操作。

自动说明符也可以与函数声明符一起使用,后跟尾随返回类型,在这种情况下,声明的返回类型是尾随返回类型(也可以是占位符类型)。

// 声明p为指向返回int的函数的指针。
auto (*p)() -> int; 		// declares p as pointer to function returning int
// 将q声明为指向返回T的函数的指针,其中T是从p的类型推导出来的。
auto (*q)() -> auto = p; 	// declares q as pointer to function returning T
                         	// where T is deduced from the type of p

auto说明符也可以在结构化绑定声明中使用。(自C ++ 17起)。
auto 关键字也可以在嵌套名称说明符中使用。 形式为auto ::的嵌套名称说明符是一个占位符,它按照约束类型占位符推导的规则由类或枚举类型替换。

案例代码分析

#include <iostream>
#include <utility>
 
// 返回类型是operator +(T,U)的类型。
template<class T, class U>
auto add(T t, U u) { return t + u; } 	// the return type is the type of operator+(T, U).
 
// perfect forwarding of a function call must use decltype(auto)
// in case the function it calls returns by reference
// 函数调用的完美转发必须使用decltype(auto),以防其调用的函数通过引用返回。
template<class F, class... Args>
decltype(auto) PerfectForward(F fun, Args&&... args) 
{ 
    return fun(std::forward<Args>(args)...); 
}

// C ++ 17自动参数声明
template<auto n> // C++17 auto parameter declaration
auto f() -> std::pair<decltype(n), decltype(n)> // auto can't deduce from brace-init-list
{
	// 无法从brace-init-list推断出auto
    return {n, n};
}
 
int main()
{
    auto a = 1 + 2;            		// type of a is int (a的返回类型是int)
    auto b = add(1, 1.2);      		// type of b is double (b的返回类型是double)
    static_assert(std::is_same_v<decltype(a), int>);
    static_assert(std::is_same_v<decltype(b), double>);
 
 	// c0的类型为int,持有a的副本
    auto c0 = a;             // type of c0 is int, holding a copy of a
    // c1的类型为int,持有a的副本
    decltype(auto) c1 = a;   // type of c1 is int, holding a copy of a
    // c2的类型是int&,是a的别名
    decltype(auto) c2 = (a); // type of c2 is int&, an alias of a
    std::cout << "a, before modification through c2 = " << a << '\n';
    ++c2;
    std::cout << "a, after modification through c2 = " << a << '\n';
 
    auto [v, w] = f<0>(); // structured binding declaration(结构化绑定声明)
 	
 	// OK:d的类型为std :: initializer_list <int>
    auto d = {1, 2}; // OK: type of d is std::initializer_list<int>
    // OK:n的类型为std :: initializer_list <int>
    auto n = {5};    // OK: type of n is std::initializer_list<int>
    // 从C ++ 17开始的错误,之前为std :: initializer_list <int>
//  auto e{1, 2};    // Error as of C++17, std::initializer_list<int> before
	// OK:从C ++ 17开始,m的类型为int,在之前的initializer_list <int>
    auto m{5};       // OK: type of m is int as of C++17, initializer_list<int> before
    // 错误:{1,2}不是表达式
//  decltype(auto) z = { 1, 2 } // Error: {1, 2} is not an expression
 
 	// auto通常用于未命名类型,例如lambda表达式的类型。
    // auto is commonly used for unnamed types such as the types of lambda expressions
    auto lambda = [](int x) { return x + 3; };
 
 	// C ++ 98中是有效的,自C ++ 11起出现错误。
//  auto int x; // valid C++98, error as of C++11
	// C 中是有效的,C ++ 中出现错误。
//  auto x;     // valid C, error in C++
}

案例代码运行结果:

a, before modification through c2 = 3
a, after modification through c2 = 4

自己编写的代码中使用分析
     想到写这篇文章的原因也是因为自己工程代码中,会时不时遇到这样的写法:


// Deal with indices
auto nIdxCountToAdd = nCount;
auto && indices = newPNode->getINdices();

indeces.resize(nIdxCountToAdd  * 2 - 2);

for (decltype(nIdxCountToAdd ) i = 0; i < nIdxCountToAdd - 1; ++i) 
{
	indices[i * 2] = (TZINT32)(i);
	indices[i * 2 + 1] = (TZINT32)(i + 1);
}


就是用 nIdxCountToAdd 确定循环变量i的类型的一个过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值