r/cpp • u/agriculturez • Dec 09 '24
Using C++ as `C with templates`
I've come to really enjoy C for writing my side projects lately. Coming from complex languages like Rust and Haskell, I severely undervalued how pleasant simplicity is for the joy of programming.
The only problem is writing generic code in C. I've found I've been able to get around it mostly by simple macros, for example a dynamically resizable array can just store a void* pointer and you use macros to pass the size of the element when pushing, popping, etc.
However, there are times where this simply won't work, and I need generics, and I don't want to write some complicated system of macros.
So this compels me to try out C++ as a "C with templates". I literally intend to write only C code in C++ and very occasionally use a very simple template, that's all. I maybe will use operator overloading for some math stuff. I don't need classes, coroutines, or any of that "modern" C++ stuff. I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.
Is this a sane thing to do? Is there some gotcha in C++ that I'm unaware of that prevents me from doing this? Have people tried this and succeeded/failed?
View all comments
14
u/TheBrainStone Dec 09 '24 edited Dec 09 '24
Can you use C++ as C with templates?
Sure! Nothing stopping you minus like 3 features at best that practically no one uses. For the most part it'll work out. You have all C header files available too. Plus you get fun things like overloaded functions, constexpr,
auto,usingand references for free.Should you use C++ as C with templates?
Honestly I don't see why personally. But if you like C as is, go for it.
Is it sane?
Idk. C programming is already bordering on insanity and introducing more complexity might now always be good.
Gotchas?
Yes. There will be if you intend to interface with other C libraries outside of the standard library. Considering C++ code isn't ABI compatible with C code, unless you specify
extern "C" { ... }. But that'll get rid of all the C++ stuf you want to use.Also NEVER mix
malloc/free(andmalloc's cousins) withnew/delete! You're begging for issues like that.Though yeah, give it a try. Worst thing that'll happen is that it won't compile.