C++11几个常用关键字auto、decltype、追踪返回类型、using

版权声明:guojawee https://blog.csdn.net/weixin_36750623/article/details/84848739

auto

1、auto关键字
(1)auto的作用是让编译器自动推断变量的类型,而不需要显式指定类型。这种隐式类型的推导发生在编译期。
(2)auto并不能代表实际的类型声明,只是一个类型声明的“占位符”
(3)auto声明的变量必须马上初始化,以让编译器推断出它的实际类型。
2、auto的限制
(1)auto不能用于函数参数。如果需要泛型参数,可借助于模板
(2)auto不能用于非静态成员变量
(3)auto无法定义数组
(4)auto无法推导模板参数

decltype关键字

decltype可以在编译期推导出一个变量或表达式的结果类型(但不会真正计算表达式的值),并且使用这个结果定义新的变量。

追踪返回类型

先看一个错误的案例:代码想推导出返回值(t + u)类型,为什么编译错误?
答:因为编译器是从左向右读入符号,此时t/u并没有读入,因此不能推导t+u的类型

template<typename R, typename T, typename U>
decltype(t + u) add(T t, U u)  
{
    return t + u;
}

解决方案:使用auto + decltype,实现 返回类型后置/追踪返回类型
返回类型后置(又称为追踪返回类型)的语法格式
  ①函数指针的等价:如,auto (*fp)() -> int 与int (*fp)()的等价;
  ②函数引用的等价:如,auto (&fr)() -> int 与 int (&fr)()的等价

template<typename R, typename T, typename U>
auto add(T t, U u) -> decltype(t + u) //返回类型后置
{
    return t + u;
}

using取代typedef

1、typedef和using关键字
  ① C++11引入using关键字,它覆盖了typedef的全部功能。采用类似于赋值的方式,从语法比typedef更加清晰。
  ② using可以轻松地为模板重定义别名

//重命名unsigned int为uint_t,两者等价
typedef unsigned int uint_t;
using uint_t = unsigned int;

//重命名std::map,两者等价
typedef std::map<std::string, int> map_int_t;  
using map_int_t = std::map<std::string, int>;  

//重命名函数指针,两者等价
typedef void(*func_t)(int, int);
using func_t = void(*)(int, int);

猜你喜欢

转载自blog.csdn.net/weixin_36750623/article/details/84848739