C++学习(一):现代C++尝试

  C++是一门与时俱进的语言。 早期的C++关注的主要问题是通用性,却没有太多关注易用性的问题,使得C++成为了一门多范式语言,但是使用门槛较高。

  从2011开始,C++的标准进行了较大的更新,开始更多地关注易用性。通常,2011年的C++标准称为C++11,又称为C++0X。目前,C++的标准基本上每三年更新一次,因此有了2014的C++14,以及今年即将发布C++17标准。如果继续是三年发布一个标准,可以预期,在2020会有C++20标准。目前GCC 6.1开始已经默认默认使用 C++14 标准。

  现代C++的详细内容请参考维基百科或者http://en.cppreference.com或者MSDN的介绍:欢迎回到 C++(现代 C++)

  本篇将举一个简单的例子,通过四个特性,说明现代C++的魅力。如下:

 1 #include <iostream>
 2 #include <vector>
 3 #include <utility>
 4 
 5 using namespace std;
 6 int main()
 7 {
 8     //1.`Range For` And `Auto` (since C++11)
 9     char str[] = "hello";
10     for (auto ch : str)cout << ch;
11     cout << endl;
12 
13     //2.`using` for `type alias` (since C++11)
14     using vecint = vector<int>;
15     vecint ivec;
16     for (auto ele : { 1,2,3 })ivec.push_back(ele);
17     for (auto ele : ivec)cout << ele << endl;
18 
19     //3.Generalized lambda (since C++14)
20     auto f = [](auto x, auto y) {return x + y; };
21     auto g = [](auto func, auto z) {return func(3, z) + 4; };
22     auto apply = [](auto func, auto ele) {return func(ele); };
23     auto square = [](auto ele) {return ele*ele; };
24     cout << f(2, 3) << endl;
25     cout << g(f, 5) << endl;
26     auto s = f(string("hello"), string(" world"));
27     //cout << s << endl;
28     cout << s.c_str() << endl; //MSVC error for `s`
29     cout << apply(square, 8.1) << endl;
30 
31     //4.Structured binding declaration (since C++17)
32     auto a = "hello";
33     auto b = "world";
34     auto swap = [](auto x, auto y) {return make_pair(y, x); };
35     auto [c, d] = swap(a, b);
36     cout << c << endl << d << endl;
37 }

 

  编译: $ g++ -std=c++14 main.cpp 

  输出:

$ ./a
hello
1
2
3
5
12
hello world
65.61

涉及的四个特性

  1.Range-based for loop (since C++11)

  基于范围的for循环在很多语言早就有了,比如Python,Java1.5+。这是一个易用特性。

  2.'using'关键字用于别名 (since C++11)

  using增加了新用法,算是老词新意,用于简化过长的类型声明,目前Java依然没有这个特性。

  3.Generalized lambda (since C++14)

  泛型Lambda,有一点类似C++中模版,在这里比模版简洁。

  4.Structured binding (since C++17)

  结构化绑定声明,是指在一次声明中同时引入多个变量,同时绑定初始化表达式的各个子对象的语法形式。

小结:

  这个例子给我的感觉是,如果连auto都可以省略掉的话,这语法基本上就类似Python了。这也说明,C++开始吸收其他语言的优点,成为一门越来越现代化的语言。目前,越来越多的新项目开始使用C++的新特性。为了避免落后,我们有必要重新认识C++。

posted @ 2017-01-19 20:09  星云的彼岸  阅读(942)  评论(0编辑  收藏  举报