Wednesday, September 19, 2007

Generics, another type of metaprogramming

This is probably obvious for most of you, but since I didn’t realize it until now, I will bring it to your attention. This C++ tutorial about templates http://www.cplusplus.com/doc/tutorial/templates.html points out that templates is compiled on demand. Close to the end of the article it states;

“From the point of view of the compiler, templates are not normal functions or classes. They are compiled on demand, meaning that the code of a template function is not compiled until an instantiation with specific template arguments is required. At that moment, when an instantiation is required, the compiler generates a function specifically for those arguments from the template.”

So what you do when you build templates in C++ is utilizing the metaprogramming paradigm in compile time. Now, referring to one of my earlier posts called Metaprogramming, I quote Wikipedia who states;

“Not all metaprogramming involves generative programming. If programs are modifiable at runtime (such as in Lisp, Python, Smalltalk, Ruby, PHP, Perl, and Tcl), then techniques can be used to perform metaprogramming without actually generating source code.”

I realize that the languages spoken of in the Wikipedia may perform other types of runtime metaprogramming, also any or none of these languages may or may not utilize generics. However looking at this text, I figure that metaprogramming is clearly a component in generics, even if it is done in runtime or compile time. One could argue that the programmer should be able to choose if a certain implementation of generics should be evaluated in compile time or runtime.

Finally, would it not be possible to define the functionality of generics if the possibility of generic metaprogramming, compile time or runtime, is available in the given language? If so, would you regard generics as a programming pattern rather than a programming paradigm? Are there more programming paradigms that we could squeeze under the roof of metaprogramming?

PS: I should bring my selfe to compile a generics example in C# and take a look at the resulting IL.

No comments: