"In C++ it's harder to shoot yourself in the foot, but when you do, you blow off your whole leg." by the god-father Bjarne Stroustrup, or
"Writing in C or C++ is like running a chain saw with all the safety guards removed," , or
"C(++) is a write-only, high-level assembler language." or even this :
"C++ : Hard to learn and built to stay that way !!" , and this :
"How C++ is like teenage sex:
- It is on everyone's mind all the time.
- Everyone talks about it all the time.
- Everyone thinks everyone else is doing it.
- Almost no one is really doing it.
- The few who are doing it are: A. Doing it poorly. B. Sure it will be better next time. C. Not practicing it safely."
Most people think that some of the coolest feature of C++ is it's templates.They are increasingly found to be powerful instruments for the development of cleaner, faster and smarter software. Indeed, templates have become the corner stone of several new C++ programming paradigms.Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
Ok , that's great, but i would say that actually the good'old C macros are just as cool as C++ templates. Generic programming and templates in C ? Yes it's pretty much possible, with a bit of macros involved :) Here's an example i wrote to test my wheel reinvention deduction.It's a basic attempt to replace the C++ STL vector<> container.
Sorry about the code formatting.
#define VECTOR(type) struct type##_Vector \ { public : type *pArray; int len; type illegal; \ type##_Vector() { len = 0; pArray = NULL; }; \ void ClearAll() { memset(pArray, 0, sizeof(type) * len); \ len = 0; }; void Erase() { if(pArray != NULL) \ free(pArray); len = 0; pArray = NULL; }; \ int push_back(type Data) { \ type* pTmp = (type*)malloc(sizeof(type) * len + sizeof(type) ); \ if(pTmp == NULL) return -1; \ memcpy(pTmp, pArray, sizeof(type) * len); free(pArray); \ pArray = pTmp; pArray[len] = Data; return len++; }; \ void SetItemAt(int pos, type data) \ { if((pos > -1) && (pos <= len)) \ { pArray[pos] = data; } } \ type GetItemAt(int pos) { if((pos > -1) && (pos <= len)) \ return pArray[pos]; return illegal; \ } \ } int main(int argc, char* argv[]) { VECTOR(int) v; v.push_back(14); v.push_back(77); class test { public : char name[64]; test(){strcpy(name ,"wtf"); }; void setName(char* Name){strcpy(name,Name);}; }; VECTOR(test) vtest; test t; vtest.push_back(t); printf(vtest.GetItemAt(0).name); vtest.Erase(); v.Erase(); return 0; }
No comments:
Post a Comment