C++ 11 auto & decltype
来源:互联网 发布:qq拼音打字软件 编辑:程序博客网 时间:2024/05/17 06:25
http://www.cnblogs.com/hujian/archive/2012/02/15/2352050.html
【原】C++ 11 auto & decltype
C++ 11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++ 98中的标识临时变量的语义,由于使用极少且多余,在C++ 11中已被删除。
auto自动类型推断,用于从初始化表达式中推断出变量的数据类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。
auto a; // 错误,没有初始化表达式,无法推断出a的类型
auto int a = 10; // 错误,auto临时变量的语义在C++ 11中已不存在
auto a = 10;
auto c = 'A';
auto s("hello");
vector<int> vctTemp;
auto it = vctTemp.begin();
auto ptr = [](){ cout << "hello world" << endl; };
auto int a = 10; // 错误,auto临时变量的语义在C++ 11中已不存在
auto a = 10;
auto c = 'A';
auto s("hello");
vector<int> vctTemp;
auto it = vctTemp.begin();
auto ptr = [](){ cout << "hello world" << endl; };
另外,在使用模板技术时,如果某个变量的类型依赖于模板参数,不使用auto将很难确定变量的类型(使用auto后,将由编译器自动进行确定)。下面是一个具体的例子。
template <class T, class U>
void Multiply(T t, U u)
{
auto v = t*u;
}
void Multiply(T t, U u)
{
auto v = t*u;
}
auto返回值占位,主要与decltype配合使用,用于返回值类型后置时的占位。
template <class T, class U>
auto Multiply(T t, U u)->decltype(t*u)
{
typedef decltype(t*u) NewType;
NewType *pResult = new NewType(t*u);
return *pResult;
}
auto Multiply(T t, U u)->decltype(t*u)
{
typedef decltype(t*u) NewType;
NewType *pResult = new NewType(t*u);
return *pResult;
}
至于为什么需要将返回值类型后置,这里简单说明一下。如果没有后置,则函数声明为decltype(t*u) Multiply(T t, U u),但此时模板参数t和u还未声明,编译无法通
过。另外,如果非要使用返回值类型前置的形式,也可以将函数声明为decltype((*(T *)0)*(*(U *)0)) Multiply(T t, U u),但这种形式比较晦涩难懂,因此不推荐采用。
0 0
- C语言11中的auto和decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++11 auto&decltype
- C++11 auto 和decltype
- C++11 auto and decltype
- C++11 auto 和 decltype
- C++11 decltype 和auto
- C++primer---constexpr、类型别名、auto、decltype
- C++11学习:auto和decltype
- c++11新特性---auto 与 decltype
- C++11的auto和decltype关键字
- C++11 auto和decltype推导规则
- C++11学习笔记3---auto&decltype
- C++11之auto、decltype关键字
- C++11的auto和decltype关键字
- C++11的auto与decltype
- Swift内存管理-示例讲解
- 拉普拉斯矩阵
- Java中class的getName()和getCanonicalName()两个方法的区别
- C++ 11 Lambda表达式
- ListView回收机制相关分析
- C++ 11 auto & decltype
- 阿里云服务使用感受
- C++ 11完美转发
- java进阶(四):Java注解学习
- 将网站发布到IIS上 也适用于将webservice发布到iis
- IOS成长之路-UIButton定义和设置圆角
- 程序员在路上
- android 界面知识点
- C++ 11语法甜点1