C++模板元编程(英文版)
C++模板元编程,来源与Boost的MPL库的经验总结,对C++模板元编程进行了深入细致的讲解。已经证明C++模板是图灵完备的。强烈建议学习C++的朋友看一下。
基本信息
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
By David Abrahams, Aleksey Gurtovoy
Publisher : Addison Wesley Professional
Pub Date : December 10, 2004
ISBN : 0-321-22725-5
Pages : 400
词汇解释
元编程(Metaprogramming): 编程序的程序.
C++模板元编程(Templete Metaprogramming): 使用C++模板技术来实现编译期类型选择/数值计算等,从而提高代码的灵活性和提高数学运算的性能。C++模板元编程技术已经被应用于多个高性能数学运算库的实现,并取得了显著效果。准C++库Boost提供了体系完整的MPL(Meta Program Lib. )库,并大量使用了这种技巧是底层库的实现更灵活高效。
简介
"If you're like me, you're excited by what people do with template metaprogramming (TMP) but are frustrated at the lack of clear guidance and powerful tools. Well, this is the book we've been waiting for. With help from the excellent Boost Metaprogramming Library, David and Aleksey take TMP from the laboratory to the workplace with readable prose and practical examples, showing that "compile-time STL" is as able as its runtime counterpart. Serving as a tutorial as well as a handbook for experts, this is the book on C++ template metaprogramming."Chuck Allison, Editor, The C++ Source
C++ Template Metaprogramming sheds light on the most powerful idioms of today's C++, at long last delivering practical metaprogramming tools and techniques into the hands of the everyday programmer.
A metaprogram is a program that generates or manipulates program code. Ever since generic programming was introduced to C++, programmers have discovered myriad "template tricks" for manipulating programs as they are compiled, effectively eliminating the barrier between program and metaprogram. While excitement among C++ experts about these capabilities has reached the community at large, their practical application remains out of reach for most programmers. This book explains what metaprogramming is and how it is best used. It provides the foundation you'll need to use the template metaprogramming effectively in your own work.
This book is aimed at any programmer who is comfortable with idioms of the Standard Template Library (STL). C++ power-users will gain a new insight into their existing work and a new fluency in the domain of metaprogramming. Intermediate-level programmers who have learned a few advanced template techniques will see where these tricks fit in the big picture and will gain the conceptual foundation to use them with discipline. Programmers who have caught the scent of metaprogramming, but for whom it is still mysterious, will finally gain a clear understanding of how, when, and why it works. All readers will leave with a new tool of unprecedented power at their disposalthe Boost Metaprogramming Library.
前言
In 1998 Dave had the privilege of attending a workshop in Generic Programming at Dagstuhl Castle in Germany. Near the end of the workshop, a very enthusiastic Kristof Czarnecki and Ullrich Eisenecker (of Generative Programming fame) passed out a few pages of C++ source code that they billed as a complete Lisp implementation built out of C++ templates. At the time it appeared to Dave to be nothing more than a curiosity, a charming but impractical hijacking of the template system to prove that you can write programs that execute at compile time. He never suspected that one day he would see a role for metaprogramming in most of his day-to-day programming jobs. In many ways, that collection of templates was the precursor to the Boost Metaprogramming Library (MPL): It may have been the first library designed to turn compile-time C++ from an ad hoc collection of "template tricks" into an example of disciplined and readable software engineering. With the availability of tools to write and understand metaprograms at a high level, we've since found that using these techniques is not only practical, but easy, fun, and often astoundingly powerful.
Despite the existence of numerous real systems built with template metaprogramming and the MPL, many people still consider metaprogramming to be other-worldly magic, and often as something to be avoided in day-to-day production code. If you've never done any metaprogramming, it may not even have an obvious relationship to the work you do. With this book, we hope to lift the veil of mystery, so that you get an understanding not only of how metaprogramming is done, but also why and when. The best part is that while much of the mystery will have dissolved, we think you'll still find enough magic left in the subject to stay as inspired about it as we are.
Dave and Aleksey
摘录
1.2. So What's a Metaprogram? (什么是元编程)
If you dissect the word metaprogram literally, it means "a program about a program."[1] A little less poetically, a metaprogram is a program that manipulates code. It may be an odd-sounding concept, but you're probably already familiar with several such beasts. Your C++ compiler is one example: it manipulates your C++ code to produce assembly language or machine code.
(1) In philosophy and, as it happens, programming, the prefix "meta" is used to mean "about" or "one level of description higher," as derived from the original Greek meaning "beyond" or "behind."
Parser generators such as YACC [Joh79] are another kind of program-manipulating program. The input to YACC is a high-level parser description written in terms of grammar rules and attached actions brace-enclosed. For instance, to parse and evaluate arithmetic expressions with the usual precedence rules, we might feed YACC the following grammar description:
expression : term
| expression '+' term { $$ = $1 + $3; }
| expression '-' term { $$ = $1 - $3; }
;
term : factor
| term '*' factor { $$ = $1 * $3; }
| term '/' factor { $$ = $1 / $3; }
;
factor : INTEGER
| group
;
group : '(' expression ')'
;
In response, YACC would generate a C/C++ source file containing (among other things), a yyparse function that we can call to parse text against the grammar and execute the appropriate actions:[2]
(2) This is provided that we also implemented an appropriate yylex function to tokenize the text. See Chapter 10 for a complete example or, better yet, pick up a YACC manual.
int main()
{
extern int yyparse();
return yyparse();
}
The user of YACC is operating mostly in the domain of parser design, so we'll call YACC's input language the domain language of this system. Because the rest of the user's program typically requires a general-purpose programming system and must interact with the generated parser, YACC translates the domain language into the host language, C, which the user then compiles and links together with her other code. The domain language thus undergoes two translation steps, and the user is always very conscious of the boundary between it and the rest of her program.
1.4. Metaprogramming in C++ (C++模板元编程)
In C++, it was discovered almost by accident [Unruh94], [Veld95b] that the template mechanism provides a rich facility for native language metaprogramming. In this section we'll explore the basic mechanisms and some common idioms used for metaprogramming in C++.
1.4.1. Numeric Computations
The earliest C++ metaprograms performed integer computations at compile time. One of the very first metaprograms was shown at a C++ committee meeting by Erwin Unruh; it was actually an illegal code fragment whose error messages contained a sequence of computed prime numbers!
Since illegal code is hard to use effectively in a larger system, let's examine a slightly more practical application. The following metaprogram (which lies at the heart of our little compiler test above) transliterates unsigned decimal numerals into their binary equivalents, allowing us to express binary constants in a recognizable form.
template <unsigned long N>
struct binary
{
static unsigned const value
= binary<N/10>::value << 1 // prepend higher bits
| N%10; // to lowest bit
};
template <> // specialization
struct binary<0> // terminates recursion
{
static unsigned const value = 0;
};
unsigned const one = binary<1>::value;
unsigned const three = binary<11>::value;
unsigned const five = binary<101>::value;
unsigned const seven = binary<111>::value;
unsigned const nine = binary<1001>::value;
If you're wondering "Where's the program?" we ask you to consider what happens when we access the nested ::value member of binary<N>. The binary template is instantiated again with a smaller N, until N reaches zero and the specialization is used as a termination condition. That process should have the familiar flavor of a recursive function calland what is a program, after all, but a function? Essentially, the compiler is being used to interpret our little metaprogram.
Error Checking
There's nothing to prevent a user from passing binary a number such as 678, whose decimal representation is not also valid binary. The result would make a strange sort of sense (it would be 6x22 + 7x21 + 8x20), but nonetheless an input like 678 probably indicates a bug in the user's logic. In Chapter 3 we'll show you how to ensure that binary<N>::value only compiles when N's decimal representation is composed solely of 0s and 1s.
Because the C++ language imposes a distinction between the expression of compile-time and runtime computation, metaprograms look different from their runtime counterparts. As in Scheme, the C++ metaprogrammer writes her code in the same language as the ordinary program, but in C++ only the compile-time subset of the full language is available to her. Compare the previous example with this straightforward runtime version of binary:
unsigned binary(unsigned long N)
{
return N == 0 ? 0 : N%10 + 2 * binary(N/10);
}
A key difference between the runtime and compile time versions is the way termination conditions are handled: our meta-binary uses template specialization to describe what happens when N is zero. Terminating specializations are a common characteristic of nearly all C++ metaprograms, though in some cases they will be hidden behind the interface of a metaprogramming library.
Another important difference between runtime and compile time C++ is highlighted by this version of binary, which uses a for loop in lieu of recursion.
unsigned binary(unsigned long N)
{
unsigned result = 0;
for (unsigned bit = 0x1; N; N /= 10, bit <<= 1)
{
if (N%10)
result += bit;
}
return result;
}
Though more verbose than the recursive version, many C++ programmers will be more comfortable with this one, not least because at runtime iteration is sometimes more efficient than recursion.
The compile-time part of C++ is often referred to as a "pure functional language" because of a property it shares with languages such as Haskell: (meta)data is immutable and (meta)functions can have no side effects. As a result, compile-time C++ has nothing corresponding to the non-const variables used in runtime C++. Since you can't write a (non-infinite) loop without examining some mutable state in its termination condition, iteration is simply beyond reach at compile time. Therefore, recursion is idiomatic for C++ metaprograms.
1.4.2. Type Computations
Much more important than its ability to do compile time numeric computations is C++'s ability to compute with types. As a matter of fact, type computation will dominate the rest of this book, and we'll cover examples of it in the very first section of the next chapter. By the time we're through, you'll probably think of template metaprogramming as "computing with types."
Although you may have to read Chapter 2 to understand the specifics of type computation, we'd like to give you a sense of its power. Remember our YACC expression evaluator? It turns out we don't need to use a translator to get that kind of power and convenience. With appropriate surrounding code from the Boost Spirit library, the following legal C++ code has equivalent functionality.
expr =
( term[expr.val = _1] >> '+' >> expr[expr.val += _1] )
| ( term[expr.val = _1] >> '-' >> expr[expr.val -= _1] )
| term[expr.val = _1]
;
term =
( factor[term.val = _1] >> '*' >> term[term.val *= _1] )
| ( factor[term.val = _1] >> '/' >> term[term.val /= _1] )
| factor[term.val = _1]
;
factor =
integer[factor.val = _1]
| ( '(' >> expr[factor.val = _1] >> ')' )
;
Each assignment stores a function object that parses and evaluates the bit of grammar on its right hand side. The behavior of each stored function object, when invoked, is determined entirely by the type of the expression used to construct it, and the type of each expression is computed by a metaprogram associated with the various operators used.
Just like YACC, the Spirit library is a metaprogram that generates parsers from grammar specifications. Unlike YACC, Spirit defines its domain language as a subset of C++ itself. If you don't see how that's possible at this point, don't worry. By the time you finish this book, you will.
下载
Addison.Wesley.C.Plus.Plus.Template.Metaprogramming.Dec.2004.chm
相关推荐
Addison Wesley - C++ Template Metaprogramming Concepts Tools And Techniques From Boost And Beyond
Addison Wesley - C++ Template Metaprogramming Concepts Tools And Techniques From Boost And Beyond
《C++ Template Metaprogramming》译序——经典之后的经典
https://blog.youkuaiyun.com/pongba/article/details/90643 ——写在C++图书出版史上又一部经典著作问世之前 刘未鹏 /文 C++图书界沉寂久矣! 至少我是这么认为的。国内引进第一批C++经典书籍的时候我是亲历的。感觉真是“忽如一夜春风来,千树万树梨花开”。别误会,我说的这个第一批并非《C++ Programming Language》...
(C++元编程)C++ Template Metaprogramming Concepts, Tools, and Techniques from Boost and Beyond.chm
C++元编程参考 英文版计算机编程经典教材 适合学习软件构造的人参考
C++元编程和Boost编程库 (C++ Metaprogramming and Boost MPL )上部
整理自http://kuibyshev.bokee.com/1584716.html 引论 C++的发展史是一个不断吸收程序设计领域精华和不断积累充实语言特性的过程。它的创造者Stroustrup在这门新的编程语言草创之初就定下了几个基本的目标,二十年过去了,至今这些目标仍然是C++继续发展的指南针。其中他明确指出,这种语言不应强迫程序员使用单一程序设计形式[20]
华硕主板UEFI模式下安装Ubuntu与Windows双系统全攻略
本文详细讲解了在华硕主板UEFI模式下安装Ubuntu与Windows双系统的完整流程。从安装前的BIOS关键设置(如处理安全启动与CSM)、使用GPT分区表,到在Windows中安全分配空间、手动创建Ubuntu分区,最后完成引导配置,提供了避免常见错误的实用技巧,确保双系统稳定共存。
基于NXP1778的CAN自动波特率检测
一、概念 NXP1778芯片内部自带一个CAN控制器。CAN模块由两部分组成:控制器和验收滤波器。所有的寄存器和RAM都以32位字宽度来访问。 CAN自动波特率检测主要用于以一种CAN的转换的产品中。产品中CAN部分的波特率以前都是通过网页中修改然后配置下去的,依据实际情况的考虑,如果CAN部分的波特率能够根据客户设备的改变而自动改变,将会增加其灵活性。 二、原理 根据CAN控制器的
C++元编程和Boost编程库 (C++ Metaprogramming and Boost MPL )
引论 C++的发展史是一个不断吸收程序设计领域精华和不断积累充实语言特性的过程。它的创造者Stroustrup在这门新的编程语言草创之初就定下了几个基本的目标,二十年过去了,至今这些目标仍然是C++继续发展的指南针。其中他明确指出,这种语言不应强迫程序员使用单一程序设计形式[20];就是说C++语言应该是一种“多种花样”的语言。正是因为Stroustrup这种高瞻远瞩的构想,才使得C
网络设备心跳线带宽高导致虚拟化平台不稳定的问题处理
本文记录了网络设备心跳线带宽高导致虚拟化平台不稳定的问题处理一例。
《C++ Template Metaprogramming》附录A——预处理元编程
《C++ Template Metaprogramming》附录A:预处理元编程 By David Abraham(http://www.boost.org/people/dave_abrahams.htm) By 刘未鹏(pongba)C++的罗浮宫(http://blog.youkuaiyun.com/pongba) 原文链接(http://www.boost-cons
JESD204B Subclass 1的SYSREF机制
SYSREF 是一个系统级同步脉冲信号,用于对齐 JESD204B 中的 LMFC(Local Multi-Frame Clock),从而实现每次建链的延迟一致性。核心点内容说明是系统参考跨多个芯片、多通道实现精确同步控制 LMFC决定所有设备的 LMFC 对齐点仅用于 Subclass 1是 JESD204B 实现确定性延迟的前提条件一般通过时钟芯片生成推荐使用 AD9528、LMK04828,支持 JESD204 专用输出建链过程中关键作用。
C# 读取图片和扫描PDF中的文本
本博客将探讨如何使用C#和OCR库实现从图片和扫描的 PDF 中提取文本。Spire.OCR for .NET 是一个OCR文字识别库,专为在 .NET 应用程序中识别图片的文本而设计。首先,使用 Spire.PDF 将扫描的 PDF 转换为图片,然后利用 Spire.OCR 从这些图片中提取文本。由于该OCR库并不支持直接处理PDF,因此要从扫描的 PDF 中提取文本,我们首先需要将 PDF 文档转换为图片。转换完成后,再利用 Spire.OCR 从生成的图片中提取文本。方法来识别图片中的文本。
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。http://blog.youkuaiyun.com/topmvp - topmvpC++ Template Metaprogramming sheds light on the most powerful idioms of todays C++, at long last delivering
采用了fluent模拟了平壁面结霜过程。udf,很经典,可以试试。
利用该模型作为FLUENT中的源项,模拟了在局部冷却下冷表面上的霜形成,以预测霜的形态、温度分布和霜的重量,结果与实验结果吻合良好。结果显示,霜首先围绕冷却块形成,然后逐渐向其他方向扩展,冷却块上方的霜密度最大。随着时间的推移,平均霜厚度逐渐增加,生长速率减慢,而平均霜密度随增长速率变快而增加。相变传递微观过程与机理、蒸发及冷凝换热、强化传热、高效传热管、热泵、制冷、节水节能新技术、电子元器件冷却、余热回收及梯级利用等。udf,很经典,可以试试。工程热物理、空调、热能、低温制冷、化工、物理等。
rails site
1 http://www.enjoyrails.com/ 2 http://blog.youkuaiyun.com/jlaky/article/details/3225587 源码分析 3 http://www.yangzhiping.com/tech/Learn-to-Program.html 4 http://thoughtrails.com/ 5 http://rubycc.com/ 6 ht...
什么是 Agent 的 Context Window?为什么它是 Agent 工程中最核心的约束之一?
什么是 Agent 的 Context Window?为什么它是 Agent 工程中最核心的约束之一?
AutosarMCAL开发——基于EB Wdg驱动
Autosar标准文件中提及的API共有5个,接口名传入参数说明返回参数函数功能ConfigPtr:Wdg配置指针,参数来自于EB生成代码voidWdg初始化ConfigPtr:Wdg配置指针Wdg初始化检查Wdg切换模式,需开启对应配置timeout:设置定时触发器计数(单位ms)void喂狗并重新设定计数值Wdg版本信息本文为博主个人学习总结记录,如有不正,欢迎指正。
good rails site
good rails site http://edgerails.info/vhttp://asciicasts.com/episodes/215-advanced-queries-in-rails-3 ...
OV9734 DATASHEET,完整规格书
OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等
每天一剂Rails良药之Manage a Static Site With Rails
对于静态站点我们可以利用Rails的cache来管理,如在controller中添加如下代码: [code] after_filter {|c| c.cache_page} [/code] 这样将会对该controller的所有action作缓存 注意我们不要对UserProfile等页面做缓存,只对对所有用户一样的内容做缓存...
温度PID控制PLC程序
温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值
计算机控制技术及应用
《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。
Ruby Plus: Another Ruby/Rails Screencast Site
Ruby Plus is a site offering free Ruby and Rails related screencasts recorded by Bala Paranj, much in the same vein as Ryan Bates' Railscasts. The screencasts are generally similar in length and o...
lwip-2.0.3
lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。
每天一剂Rails良药之Syndicate Your Site With RSS
今天来看看Rails对RSS的支持: feed_controller.rb: [code] class FeedController < ApplicationController session \:off def recipes @recipes = Recipe.find(:all, \:order =>...
rails CSS/XSS——cross-site scripting
if you use h(),it will be:otherwise: it wont be shown:also:otherwise:it functioned:
725



被折叠的 条评论
为什么被折叠?



