Templates
2000-01-01
One feature of C++ are templates. Most notable is the STL, but templates also have many other uses. In fact, they are nothing more than better macros. Anything you can do with templates in C++, you also could manage in plain C, using those ugly #define or #include tricks. You write code once, but some details of it, like certain data types or operations, can be replaced. The code is just a template, and each actual instantiation of the code will then have different things filled in.This has a big advantage: You only need to write the code once, so if something changes, then you do not have to adjust multiple versions, with the big risk of doing it wrong in one or forgetting one. Of course, the same could also be done without templates or macros, by using some runtime mechanisms to choose the right version, but that involves conditionals or lookups, and will be much slower. With templates or macros, the compiler will be able to run all of its optimizations ''after'' the code was instantiated. So in the end, there indeed will be multiple versions, but you as programmer only have to maintain one.
Still, the solution is flawed. In C, writing 'macroed' code is not nice, you probably will end up with lots of \ characters after each line, put stuff into #include files, and generally your algorithm will be much harder to read than the specialized version. Often it will be easier to e.g. maintain three separate functions stuck together in some file than having a single function using macros for the three different possibilities.
The same, unfortunately, is true for C++. No doubt, for many things, it usually is nicer to have a templated C++ version than using C macros. But it still makes the code more unreadable than using a fixed version.
This is what I solve with my approach. The idea is simply to use a meta language. So sort of a very powerful #define. I simply write my algorithm in Python, writing out the C code for the compiler to use. That way, I can do it in a way like with #defines or templates, but in many case, can do much better. That's the main idea behind scramble. Keep the simplicity of C, and get all the more powerful features by having the whole Python interpreter as preprocessor.