08 C++11中的variadic template、auto和for基本用法(学自Boolean)

来源:互联网 发布:mac如何截取长图 编辑:程序博客网 时间:2024/06/16 17:13

1、引言

C++11中增加了不少新的特性,本篇主要介绍variadic templates(数量不定的模板参数)、auto和ranged-base for的用法。

2、variadic templates

1)示例

void print(){} //#1template <typename T, typename... Types>void print(const T& firstArg, const Types&... args){std::cout << firstArg << std::endl;print(args...);} #2
注意点:

a、本例是通过数量不定的模板参数。设计print()打印函数;

b、使用固定格式typename... 来定义数量不定的模板参数;

c、在#2设计中,第一个参数firstArg为传入的第一个值,后面参数为其它的参数包;

d、使用递归的方式进行打印输出,格式也为固定格式(args...);

e、当print(args...)中的args为空时,执行#1的print(),此时函数执行完毕。

2)主程序使用

int _tmain(int argc, _TCHAR* argv[]){print(10, "yes", 'a');return 0;}/*输出结果:10yesa*/
说明:主程序会依次输出打印结果。

3、auto的用法

auto的用法类似于C#中的var,匿名变量。

1)示例

int _tmain(int argc, _TCHAR* argv[]){int a = 10;auto b = a + 5;std::cout << b << std::endl;return 0;}/*输出结果:15*/
注意点:

a、程序中b变量类型编译器会根据操作数自动匹配;

b、使用auto变量声明,必须要赋初值。

4、ranged-base for

这是C++11中对for循环的一种新用法。

1)使用格式

for (del : coll){statement;}
说明:coll为容器,在遍历过程中,容器中的值会以值或引用传给del,如下图:


2)示例

int _tmain(int argc, _TCHAR* argv[]){for (int i : {1, 2, 3, 4, 5}){std::cout << i << " ";}return 0;}/*输出结果:1 2 3 4 5*/




阅读全文
0 0
原创粉丝点击