Template C++(www.cppentry.com). This is the generic programming part of C++(www.cppentry.com), the one that most programmers have the least experience with. Template considerations pervade C++(www.cppentry.com), and it’s not uncommon for rules of good programming to include special template-only clauses(e.g., see Item 46 on facilitating type conversions in calls to template functions). In fact, templates are so powerful, they give riseto a completely new programming paradigm, template metaprogramming(TMP). Item 48 provides an overview of TMP, but unless you’re a hard-core template junkie, you need not worry about it. The rules for TMP rarely interact with mainstream C++(www.cppentry.com) programming.
The STL. The STL is a template library, of course, but it’s a very special template library. Its conventions regarding containers, iterators, algorithms, and function objects mesh beautifully, but templates and libraries can be built around other ideas, too. The STL has particular ways of doing things, and when you’re working with the STL, you need to be sure to follow its conventions.
C++(www.cppentry.com)不是绝对意义上的C++(www.cppentry.com)。在本书的第二版中没有Item 1这一节,而在这一版中,把这一大段放在了第一条,可见作者对这个问题的重要性也是逐步才认识到的。我对此深以为然。这一篇是全书的中心,读此书必须先细细品味它。如果之前读过第二版,对比一下行文风格,就能发现二者有极大差异。作者不再强调在C++(www.cppentry.com)中必须怎样做,文字中隐隐透着些许无奈,本篇就是最佳注脚。
在我看来,C++(www.cppentry.com)各个不同方面的差异性要远大于它们的共性。C++(www.cppentry.com)经过几十年发展逐渐演变成今天这样,将如此之多的编程(www.cppentry.com)风格糅合在同一门语言中,让它们能和谐共存,是非常困难的事情。因为要尽可能满足各种项目、各种用户在各种时期的不同需求,所以C++(www.cppentry.com)不是在一开始经过深思熟虑定义出来的。C++(www.cppentry.com)语言发展到今天,还能发展下去,难能可贵。所以,C++(www.cppentry.com)新标准从 1998 年到现在,十多年过去了,还未能完全定稿,真的很容易理解。
在某些C++(www.cppentry.com)教材上,反复强调不要把C++(www.cppentry.com)当成 C 使用(包括本书第二版),在某种意义上说没错。但只使用C++(www.cppentry.com)的一部分——只是C的部分,仅仅利用C++(www.cppentry.com)的改进来弥补 C 的一些缺陷,在工程实践中也是个不错的方案。如何使用C++(www.cppentry.com)最好,仅取决于你的开发团队怎样定义你们使用的C++(www.cppentry.com),并且是否全部认同。Google在这一点上做得很好,在网络上流传着Google发布的C++(www.cppentry.com)编码规范,建议大家看一看。有规范,并且大家一起遵守,比到底规范了些什么重要得多。
我在2005年到2006年间,曾经在团队中推广过一段时间类似C的C++(www.cppentry.com)子集做开发,那和我早些年编写的C++(www.cppentry.com)程序风格完全不同,也工作良好。不过这段经历使我对面向对象和模板技术做了许多反思,并最终转向彻底的纯C语言开发。
我个人觉得,应该多尝试一些不同的东西,而不要武断地把任何技术当成唯一真理。你可以热爱面向对象,也可以尝试一下Template。但需要警惕的是,虽然C++(www.cppentry.com)允许把各种不同风格的编程(www.cppentry.com)方式杂糅在一起使用,每种都提供了高性能的支持,可以取各家之所长,有种世界在我手中的感觉,甚至可以让C++(www.cppentry.com)程序员心中不断生出创新的快感,殊不知,其引起的冲突和复杂性,可以轻易超过个人能控制的范畴。尤其对于聪明的C++(www.cppentry.com)程序员,更是危险。这一点仅仅学习语言,而不经过长年的经验积累,是很难有切身体会的。