概念
Metaprogramming is writing code that writes code.
Metaprogramming is writing code that manipulates language constructs
at runtime.
可以编写代码的代码
Metaprogramming Ruby
This particular brand of metaprogramming implies that you use a program to generate or otherwise manipulate a second, distinct program—and then you run the second program.
After you run the code generator, you can actually read the generated code and (if you want to test your tolerance for pain) even modify it by hand before you finally run it. This is also what happens under the hood with C++ templates: the compiler turns your templates into a regular C++ program before compiling them, and then you run the compiled program.
code that manipulates itself at runtime. Only a few languages can do that effectively, and Ruby is one of them. You can think of this as dynamic metaprogramming to distinguish it from the static metaprogramming of code generators and compilers.
元编程是编写在运行时操纵语言构件的代码。
ActiveRecord的作者是怎样应用这个概念的?他不是为每个类的属性编写访问器方法,而是编写代码为每个继承自ActiveRecord::Base的类在运行时定义方法。这就是“编写代码的代码”时所指的东西。
一个用C语言写的程序会跨越两个不同的世界:编译时和运行时。在编译时,可以拥有像变量和函数这样的语言构件;而在运行时,只有一大堆机器码。由于绝大多数编译时的信息在运行时都丢失了,所以C语言不支持元编程或内省。在C++语言中,一些语言构件可以在编译后生存下来,这也是为什么你可以向C++对象询问它的类的原因。在Java语言中,编译时和运行时的界线甚至更加模糊,你有足够的内省能力来列出一个类的方法,或者一直向上查询其超类链。
Ruby无疑是现今流行语言中对元编程最友好的一种语言。没有编译时,Ruby程序中所有的语言构件在运行时可用。在运行一个程序时,无须翻过一道横亘在所写程序与所运行程序中间的墙。这里只有一个世界。
C++模板元编程
STL是采用模板技术实现的
As a guideline, if any three of the following conditions apply to you, a metaprogrammed solution may be appropriate.
常见的使用场景
· You want the code to be expressed in terms of the abstractions of the problem domain. For example, you might want a parser to be expressed by something that looks like a formal grammar rather than as tables full of numbers or as a collection of subroutines; you might want array math to be written using operator notation on matrix and vector objects rather than as loops over sequences of numbers.
· You would otherwise have to write a great deal of boilerplate implementation code.
· You need to choose component implementations based on the properties of their type parameters.
· You want to take advantage of valuable properties of generic programming in C++ such as static type checking and behavioral customization, without loss of efficiency.
· You want to do it all within the C++ language, without an external tool or custom source code generator.
参考
C++模板元编程
http://product.china-pub.com/48816
C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond
By David Abrahams, Aleksey Gurtovoy
Ruby元编程(松本行弘作序推荐)
http://product.china-pub.com/1147651