I am not new to programming, but I am one that started a few years ago, and I do
ID: 658990 • Letter: I
Question
I am not new to programming, but I am one that started a few years ago, and I do love templates.
But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.
There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?
Explanation / Answer
Besides the void * pointer which is covered in Robert's answer, a technique like this was used (Disclaimer: 20 year old memory):
#define WANTIMP
#define TYPE int
#include "collection.h"
#undef TYPE
#define TYPE string
#include "collection.h"
#undef TYPE
int main() {
Collection_int lstInt;
Collection_string lstString;
}
Where I have forgotten the exact preprocessor magic inside collection.h, but it was something like this:
class Collection_ ## TYPE {
public:
Collection() {}
void Add(TYPE value);
private:
TYPE *list;
size_t n;
size_t a;
}
#ifdef WANTIMP
void Collection_ ## TYPE ::Add(TYPE value)
#endif
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.