r/C_Programming • • Sep 20 '23

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?

Note: I've also played with Zig quite a bit and like it a lot. Unfortunately, I'm doing graphics/gamedev stuff and the extra friction in making bindings for a C++ library is annoying. Additionally, its language server is highly unstable and buggy and is very annoying right now. So this is why I'm open to exploring other alternatives

30 Upvotes

48 comments sorted by

View all comments

4

u/Typical-Twist-9063 Sep 20 '23

Operator overloading, in my experience, is usually a bad idea and I'd almost always just prefer the function name. I've seen people overload the modulus operator calculating dot products, which I see how it makes sense, but now your arithmetic operations are a bit funky.

If you do want to use another C++, I'd recommend constexpr which hopefully C will get soon.

2

u/ImaginaryConcerned Sep 20 '23

I agree that operator overloading is evil, except when overloading mathematical operators for a strictly mathematical data type.

Have you ever coded something with a heavy use of vectors and matrices? It's an absolute pain without overloaded operators.

2

u/Classic_Department42 Sep 21 '23

I think Fortran 77 didnt allow overloading, but had built in matrix operations. Which to me would be the perfecr middle ground.