C++11 decltype 和auto
来源:互联网 发布:零云cms 编辑:程序博客网 时间:2024/05/19 06:38
C++ decltype 自动推导类型
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 和 auto 连在一起用到的比较多 下边是参考 cppreference的列子
#include <iostream>struct A { double x; };const A* a = new A{ 0 };decltype(a->x) y; // y的类型是double(声明类型)decltype((a->x)) z = y; // z的类型是const double&(左值表达式)template<typename T, typename U>auto add(T t, U u) -> decltype(t + u); // 返回类型依赖于模板参数template<typename T,typename U>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; // lambda的类型是唯一且无名的i = f(2, 2);j = g(3, 3);std::cout << "i = " << i << ", "<< "j = " << j << '\n';}
decltype和 auto区别
auto从变量值推出类型
decltype从表达式推出类型 比如decltype(fun());他并不执行fun();
我声明一个 int x=5;
int ref=&i;
auto(ref) 是根据5推导出来 类型为 int
而decltype(ref)推导出来为 int&
同理 const int x=5 auto(x)会漏掉const 的关键字 而decltype(x)则不会
--
------------------------------------------------------------------------------------------------------------------
decltype和auto用途-
比方 我想 decltype(fun()) a;
但不需要计算fun()这个函数 就 用decltype
auto a的话 需要有一个赋值auto a = fun(x); 这样 是计算fun(x)后得出来的
auto+decltype 可以进行动态推导
template<typename T, typename U>auto add(T t, U u) -> decltype(t + u); // 返回类型依赖于模板参数上文中这个函数就是一个最常用的例子
用模板 写一个返回值为一个 类型为 t+u的列子
--------------------------------------------------------------------------------------
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); };
- C语言11中的auto和decltype
- C++11 auto 和decltype
- C++11 auto 和 decltype
- C++11 decltype 和auto
- C++11学习:auto和decltype
- C++11的auto和decltype关键字
- C++11 auto和decltype推导规则
- C++11的auto和decltype关键字
- auto和decltype
- 关于auto和decltype
- auto和decltype
- auto和decltype
- C++ auto和decltype
- auto和decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++11 auto&decltype
- Acdream
- 通俗易懂客户端与服务器端交互原理(HTTP数据请求与HTTP响应,包括Servlet部分)
- HTML笔记(HTML元素-表格与列表)
- 北京国税办税软件安装问题
- codevs 1004 四子连棋
- C++11 decltype 和auto
- (坑)网络流浅谈
- 欢迎使用CSDN-markdown编辑器
- Python(一)关于Python字符串的简单操作
- httpclient访问httpfs服务(有Kerberos认证)
- 51nod 1113 矩阵快速幂
- JAVA开发Web Service几种框架介绍
- bzoj 2324: [ZJOI2011]营救皮卡丘 费用流,最小路径覆盖DAG
- 单片机实验八