Generic programming vs. Metaprogramming
Asked Answered
L

6

22

What exactly is the difference? It seems like the terms can be used somewhat interchangeably, but reading the wikipedia entry for Objective-c, I came across:

In addition to C’s style of procedural programming, C++ directly supports certain forms of object-oriented programming, generic programming, and metaprogramming.

in reference to C++. So apparently they're different?

Lenka answered 14/10, 2010 at 21:7 Comment(5)
Offtop linguistic question: v.s. or vs.? - "v.s." versus "vs." :)Filigreed
@Armen: that also brings the question: "v.s. vs. vs." vs. "v.s. v.s. vs."?Foreordain
@Claudiu: And let the holy recursion recurse! :DFiligreed
@Armen: my stack just overflowedForeordain
("v.s. vs. vs." vs. "v.s. v.s. vs.") v.s. ("v.s. vs. vs." v.s. "v.s. v.s. vs.") v.s. ("v.s. vs. vs." vs. "v.s. v.s. vs.") vs. ("v.s. vs. vs." v.s. "v.s. v.s. vs.")Patman
D
49
  • Programming: Writing a program that creates, transforms, filters, aggregates and otherwise manipulates data.
  • Metaprogramming: Writing a program that creates, transforms, filters, aggregates and otherwise manipulates programs.
  • Generic Programming: Writing a program that creates, transforms, filters, aggregates and otherwise manipulates data, but makes only the minimum assumptions about the structure of the data, thus maximizing reuse across a wide range of datatypes.

As was already mentioned in several other answers, the distinction can be confusing in C++, since both Generic Programming and (static/compile time) Metaprogramming are done with Templates. To confuse you even further, Generic Programming in C++ actually uses Metaprogramming to be efficient, i.e. Template Specialization generates specialized (fast) programs from generic ones.

Also note that, as every Lisp programmer knows, code and data are the same thing, so there really is no such thing as "metaprogramming", it's all just programming. Again, this is a bit hard to see in C++, since you actually use two completely different programming languages for programming (C++, an imperative, procedural, object-oriented language in the C family) and metaprogramming (Templates, a purely functional "accidental" language somewhere in between pure lambda calculus and Haskell, with butt-ugly syntax, since it was never actually intended to be a programming language.)

Many other languages use the same language for both programming and metaprogramming (e.g. Lisp, Template Haskell, Converge, Smalltalk, Newspeak, Ruby, Ioke, Seph).

Disassemble answered 14/10, 2010 at 21:46 Comment(0)
F
13

Metaprogramming, in a broad sense, means writing programs that yield other programs. E.g. like templates in C++ produce actual code only when instantiated. One can interpret a template as a program that takes a type as an input and produces an actual function/class as an output. Preprocessor is another kind of metaprogramming. Another made-up example of metaprogramming:a program that reads an XML and produces some SQL scripts according to the XML. Again, in general, a metaprogram is a program that yields another program, whereas generic programming is about parametrized(usually with other types) types(including functions) .

EDITED after considering the comments to this answer

Filigreed answered 14/10, 2010 at 21:11 Comment(5)
Yes, you can think of a template as a metaprogram, but you can't really do the same with e.g. java generics. So I would say: generic programming can be achieved using metaprogramming, but that's not the only way.Affectional
@sepp2k: Well, I specified templates in C++. But I agree that in other languages generic programming must not necessarily involve metaprogrammingFiligreed
@sepp2k: this is a good point which I only implied in my answer as well. IMO an even better example than Java generics (which involve at least some cooperation from the compiler in type erasure) are generic functions in Common Lisp, in which dispatch is accomplished purely by inspection of the runtime type (IIRC, I'm not a Lisp expert, so correct me if I'm wrong).Trujillo
@Derrick: The Lisp example sounds like methods in the Common Lisp Object System. There's macros, which do metaprogramming, but they expand at compile time. I'm not sure what "generic functions" means in CL.Tonga
@David Thornley: we're talking about the same thing. As I understand it, generic functions are defined/declared by defgeneric and implemented by methods (on a class-by-class basis) with defmethod. In other words, CLOS uses "generic function" to mean what most people mean by "method" or "virtual function" and "method" to mean the specific implementation.Trujillo
T
10

I would roughly define metaprogramming as "writing programs to write programs" and generic programming as "using language features to write functions, classes, etc. parameterized on the data types of arguments or members".

By this standard, C++ templates are useful for both generic programming (think vector, list, sort...) and metaprogramming (think Boost and e.g. Spirit). Furthermore, I would argue that generic programming in C++ (i.e. compile-time polymorphism) is accomplished by metaprogramming (i.e. code generation from templated code).

Trujillo answered 14/10, 2010 at 21:13 Comment(0)
A
6

Generic programming usually refers to functions that can work with many types. E.g. a sort function, which can sort a collection of comparables instead of one sort function to sort an array of ints and another one to sort a vector of strings.

Metaprogramming refers to inspecting, modifying or creating classes, modules or functions programmatically.

Affectional answered 14/10, 2010 at 21:11 Comment(0)
D
4

Its best to look at other languages, because in C++, a single feature supports both Generic Programming and Metaprogramming. (Templates are very powerful).

In Scheme / Lisp, you can change the grammar of your code. People probably know Scheme as "that prefix language with lots of parenthesis", but it also has very powerful metaprogramming techniques (Hygenic Macros). In particular, try / catch can be created, and even the grammar can be manipulated to a point (For example, here is a prefix to infix converter if you don't want to write prefix code anymore: http://github.com/marcomaggi/nausicaa). This is accomplished through metaprogramming, code that writes code that writes code. This is useful for experimenting with new paradigms of programming (the AMB operator plays an important role in non-deterministic programming. I hope AMB will become mainstream in the next 5 years or so...)

In Java / C#, you can have generic programming through generics. You can write one generic class that supports the types of many other classes. For instance, in Java, you can use Vector to create a Vector of Integers. Or Vector if you want it specific to your own class.

Where things get strange, is that C++ templates are designed for generic programming. However, because of a few tricks, C++ templates themselves are turing-complete. Using these tricks, it is possible to add new features to the C++ language through meta-programming. Its convoluted, but it works. Here's an example which adds multiple dispatch to C++ through templates. http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html . The more typical example is Fibonacci at compile time: http://blog.emptycrate.com/node/271

Denudate answered 14/10, 2010 at 21:27 Comment(0)
M
0

Generic programming is a very simple form of metacoding albeit not usually runtime. It's more like the preprocessor in C and relates more to template programming in most use cases and basic implementations.

You'll find often in typed languages that you'll create a few implementations of something where only the type if different. In languages such as Java this can be especially painful since every class and interface is defining a new type.

You can generate those classes by converting them to a string literal then replacing the class name with a variable to interpolate.

Where generics are used in runtime it's a bit different, in that case it's simply variable programming, programming using variables.

The way to envisage that is simple, take to files, compare them and turn anything different into a variable. Now you have only one file that is reusable. You only have to specify what's different, hence the name variable.

How generics came about it that not everything can be made variable like the variable type you expect or a cast type. Often there would by a lot of file duplication where the only thing that was variable was the variable types. This was a very common source of duplication. Although there are ways around it or to mitigate it they aren't particularly convenient. Generics have come along as a kind of variable variable to allow making the variable type variable. Because the variable type is something normally expressing in the programming language that can now be specified in runtime it is also considered metacoding, albeit a very simple case.

The effect of not having variability where you need it is to unroll your variables, that is you are forced instead of having a variable to make an implementation for every possible would be variable value.

As you can imagine that is quite expensive. This would be very common when using any kind of reusage object storage library. These will accept any object but in most cases people only want to sore one type of objdct. If you put in a Shop object which extends Object then want to retrieve it, the method signature on the storage object will return simply Object but your code will expect a Shop object. This will break compilation with the downgrade of the object unless you cast it back up to shop. This raises another conundrum as without generics there is no way to check for compatibility and ensure the object you are storing is a Shop class.

Java avoids metaprogramming and tries to keep the language simple using OOP principles of polymorphism instead to make flexible code. However there are some pressing and reoccurring problems that through experience have presented themselves and are addressed with the addition of minimal metaprogramming facilities. Java does not want to be a metaprogramming language but sparingly imports concepts from there to solve the most nagging problems.

Programming languages that offer lavage metacoding facilities can be significantly more productive than languages than avoid it barring special cases, reflection, OOP polymorphism, etc. However it often also takes a lot more skill and expertise to generate un=nderstandable, maintaiable and bug free code. There is also often a performance penalty for such languages with C++ being a bit of an oddball because it is compiled to native.

Manrope answered 28/9, 2017 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.