(C++ std学习) —— auto 和 decltype的理解和使用

27 篇文章 0 订阅
16 篇文章 0 订阅

(C++ STD学习) —— auto 和 decltype的理解和使用

概述和背景

     在自己编写代码的项目中,有些地方碰到同事特别喜欢使用auto和decltype作为使用的方法,就是比较喜欢用C++11这个特性,我才发现自己之前对这方面有些抵触,我个人习惯是能不用auto就不用auto,不然一堆auto别人看了也不好理解到底是个什么类型,会导致代码可读性变的很差,不过还是意识到,虽然我个人不喜欢用,但是大趋势是同事之间会越来越多的人来使用这种C++11的新特性,所以还是要认真地看看学习一下这东西,因此就有了这篇文章的诞生。

参考文本和自行翻译

     声明: 下面这节是从英文文档中我自己想办法翻译过来学习用的!
     下面这一整节主要来自于从C++ Reference里面的学习和翻译的过程:

在这里插入图片描述

     这一段讲的是关于auto 和 decltype的一些占位符的使用说明,对于变量的类型,指定将要从其初始值设定项自动推断出要声明的变量的类型。

定义

在这里插入图片描述
     这样一个auto的占位符可能会出现在下列的情况中使用:

  • 在变量的类型说明符中:auto x = expr;。 从初始化程序推导类型。例如,给定 const auto&i = expr ;,如果编译了函数调用f(expr),则i的类型恰好是虚构模板template <class U> 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 <auto I> struct A;。 它的类型是从相应的参数推导出来的。
  • 此外,autotype-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<A1...An>则约束表达式 C o n c e p t < T , A 1 , . . . , A n > Concept <T,A_1,...,A_n> Concept<TA1...An>必须有效并返回true;;
    • 否则(类型约束是不带参数列表的Concept),约束表达式Concept <T>必须有效并返回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的类型的一个过程。

个人格言

用心去感受你自己需要坚持的生活,未来慢慢会给你答案的。

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值