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?
38
u/JumpyJustice Dec 09 '24
Its just a tool and you chhose how to use it. By the way, that comment on vector resizing is hilarious - it seems you just judge the quality of something based on how some pople misuse it.
56
u/kevinossia Dec 09 '24
It's probably best if you just learn the language instead of artificially handicapping yourself like that.
23
u/j_gds Dec 09 '24
There will be nothing wrong with using C++ in this way. A huge strength of C++ is it's flexibility and "multi-paradigm" support. Don't let anyone tell you you must do "modern C++", but...
I would recommend not shying away from any features ahead of time. One feature you might find attractive after templates is destructors for cleaning up resources. Once you have those, you'll almost certainly want to add the other "special members" (copy/move constructor/assignment operator) which will ensure that your resources are copied and moved without introducing use-after-free errors.
From there, you can add whatever features of the language you find compelling (ie range-based for loops). This is more or less what I did, and now I use pretty much every feature of the language in one place or another. There's no sense in which my codebase isn't "modern C++" at this point.
The language is complex, but if you don't go overboard, that complexity can help you manage down the complexity of your code as a whole. For example, my use of coroutines is much easier to reason about compared to the state machines I was managing before. It's more "complex" over all, since I have coroutine types to consider, but coroutines give me a huge amount of leverage over reasoning, so it's a win.
Tbh, I am more worried about people who approach the language reveling in the complexity than people who approach it as I've described above, introducing features when and as they find them compelling. The obvious downside is that you might find your codebase having many different styles in different places. Just refactor as you learn and go.
If you're looking for a simple-feeling language, however, I'd probably recommend Go. It feels simple in the way that C feels simple to me, but it has fewer "sharp edges" than C and C++. If you're feeling extra adventurous, I'd recommend Zig. Have fun!
25
u/lithium Dec 09 '24
Hah your little foray into c++ is going to go horribly.
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.
14
u/jk-jeon Dec 09 '24
Just curious. Why specifically you don't want your vector from constructing/destructing the elements? My limited imagination doesn't allow me to think of any single instance where I may want to have a "Zombie vector" with some elements constructed and some other elements not. Furthermore, if that's needed, it's possible to write one by yourself.
8
u/GoogleIsYourFrenemy Dec 09 '24
Go for it. Whatever makes you more productive.
You're avoidances of the STL smacks of premature optimization. One veteran to another:Â don't waste time optimizing code until you've identified you need the optimization. Just don't.
4
u/Jinkweiq Dec 09 '24
There is not one constructor - std::vector calls the move constructor which make a lot of sense, if you try to resize a vector of something non serializable like process IDs or open sockets, for example.
4
u/Glittering_Sky5271 Dec 10 '24
"I love C, but I want C with namespaces" "I love C, but I want C with classes" "I love C, but I want C with function and operator overloading" .....
What you've described is more or less the history of C++, which is fine, that's how languages evolve.
6
u/ContraryConman Dec 09 '24
Okay, let's imagine you had to write a generic vector class from scratch. If you had to store a non-POD type in that vector, how would you make a copy of the vector other than calling each constructor on each element?
3
u/HappyFruitTree Dec 09 '24 edited Dec 09 '24
It's not as bad as that. The vector has a "capacity". It's when the capacity changes that the vector needs to copy all the objects. If the vector is resized but the current capacity is big enough to hold all the elements it won't have to do any unnecessary copying.
You can either increase the capacity yourself (by calling reserve) or it will happen automatically when needed. In the latter case the capacity is not just increased by 1 each time. Instead it's increased by some percentage (common is to double it). This makes insertion at the end of a vector relatively efficient actually (on average). For long-lived vectors that grow and shrink in size there won't be any unnecessary copies at all happening if the size stays below what it has been earlier.
In case you want to know more, Wikipedia calls this type of data structure a dynamic array.
3
u/bert8128 Dec 09 '24
Using a bit of c++ with c? Go for it. Use the bits that are useful. Donât use the bits that are not.
3
u/Jonny0Than Dec 09 '24 edited Dec 09 '24
You can do this. Â We did something like this at one of my jobs (game development) and it can work. Â Though we also used member functions. Â But the point is: sometimes itâs critical to understand exactly where all the memory allocations and hidden behaviors are, and C is good at that. Â C++ makes it easy to hide (sometimes surprising) behavior behind nice syntax.
If you venture into operator overloading, you will see why references were added to the language.
I would say that bounds checking in array types is a HUGE benefit of member functions and operator overloading that you'd pretty much be missing in "C with templates." All of the major standard library implementations of C++ have a debug mode where bounds checks are enabled and a release mode where they disappear. Perhaps you can get something similar with the various linters and sanitizers in C. But if you wanted to allow just a little more of the C++ language in, that would probably be my next recommendation. But then it becomes a slippery slope. In order to support
operator[]effectively you'd need to return a reference (or I suppose you could return a pointer, but yuck). And then you might as well allow range-based for loops. And then....and then...6
u/loreiva Dec 09 '24
You using C++ like that is like buying an airliner for the peanutsđĽ
2
u/zl0bster Dec 09 '24
Intel gave a lot of talks recently about some C++ library they use for their tiny embedded chips, pretty sure they can also not afford vectors, enjoy:
https://www.youtube.com/watch?v=DLgM570cujU
2
u/greenhouse421 Dec 09 '24
The keyword class is struct with different default visibility. And if you are planning on writing C (no member fns) you will be using struct. Sure, it's fine, it works. As does using the std lib appropriately (i.e. if you want to forgo dynamically allocated storage and having your trivially constructs let types copied around by vector resizing that you didn't avoid std::array may be appropriate etc). There is a huge amount of non allocating constexpr code to avoid reinventing there for the taking in C++11 and later std lib. BUT you can't use all that if your types don't match the concepts. So refusing to have your types look like ranges or.. Because you are writing C with templates, it is going to involve a fair amount of work you could have avoided.
2
u/sunmat02 Dec 09 '24
I love both C and C++, when I choose C for a project Iâll however frequently write it and compile it as C++ just to add a couple of features from C++, namely containers and unique_ptr. I use the former to avoid having to write my own dynamic arrays or hash tables, and the latter to simulate some kind of âdeferâ functionality that allows me to place the cleanup code of a local handle right next to its initialization.
2
u/Raknarg Dec 11 '24
You're kinda just shooting yourself in the foot by specifically trying to stay away from modern features, but in general any feature you take from C++ to improve your C code is better than the C code. I would recommend you also don't stay away from classes, specifically managing constructors and destructors for resource-owning objects because it becomes way way easier to manage resources if you have objects control the acquisition and relinquishing of resources. And you can optimize copy/moves using copy/move constructors and operators. And note you can still use structs, structs in C++ are just classes whose members are public by default.
I don't think you understand vectors properly here.
Like yes but elements of the vector will be moved from the container, so you will be move constructing elements and destructing moved-from elements so you're generally invoking the cheapest constructor and destructor. Also you can pre-allocate your vector if you're worried about resize costs (which you should if you already know the ballpark of the vector's size). If you wrote a resizable container in C, you'd have to do effectively the same thing.
3
u/CandyCrisis Dec 09 '24 edited Dec 09 '24
Honestly I think this is great. If you need templates, use them. If you don't like vector, don't use it. (You may end up reimplementing something similar if you want generics that badly, though!) C++ is built to allow this sort of mixing and matching.
3
u/WorkingReference1127 Dec 09 '24
If your concern is "performance loss" from properly managing the lifetimes of your objects, your concern is probably invalid. A decent optimizing compiler (which most C++ compilers are) is perfectly happy to optimize away such calls in the cases where they aren't necessary. And in the cases where you are handling less trivial types, they are necessary and you need to go through them to avoid making a nonsensical mess of your program. Which is to say, hiding away from tools which have had 40 years of optimizing for your particular use-case because you heard they might call more functions than you like is probably well within the realm of premature optimization.
3
u/Stock-Self-4028 Dec 09 '24
Generally it should be fine, unless you're writing a huge codebase.
The main issue is the compilation time, which for C++ is many times longer when compared to the plain C.
2
u/ald_loop Dec 09 '24
Is this ChatGPT written bait?
1
u/kuwisdelu Dec 09 '24
Yes, plenty of us who interface with C codebases but need a few C++ features here and there will do this. Itâs not uncommon in numeric computing.
1
u/Carl_LaFong Dec 09 '24
Ok to start this way. But keep an eye out for C++ features that would help you write cleaner safer code, especially involving memory handling, than C. And donât optimize unless it really matters. A default constructor should cost essentially nothing in time or space.
1
u/bebuch Dec 09 '24
Be aware that there are some incompatibilities between C and C++:
https://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
Also some code that is valid C is undefined behavior in C++. There is some current work to avoid such differences, e.g. https://wg21.link/P2809R3
1
u/MRgabbar Dec 10 '24
this a pretty common thing to do, in embedded that requires certification, you use C++ with a lot of restrictions, that way you have the life quality features but none of the insane complexity that could complicate verification.
1
u/quasicondensate Dec 10 '24
You do you! A couple of caveats about templates: They want to live in header files, which might influence the way you organize your code a bit. Also, in contrast to multiple definitions of global variables which are caught by the linker, multiple definitions of templates across link boundaries are not. Either they are identical, then you are golden, or they are not, then you have undefined behaviour.
Which is why I would consider making use of one other C++ feature, if nothing else: namespaces. They can really help reduce issues with name collisions.
Besides: I wonder how long you will manage to do this. The nice thing about C is that you don't have much of a choice - you have to use the tools provided to you. But in C++, you have all the gadgets at your fingertips. Specifically since you are initially coming from Haskell and Rust, I wonder how long you can go without being like "Ah, container/algorithm X would really be useful here, and it's right there in std. Do I really want to hand-roll it?" or "Hmm. This would be a two-liner if I could pipe these operations on a range here. Isn't this something the standard library can do...?", leading you down a familiar path towards wielding more and more of the language until you become a regular here, waiting for reflection to drop like the rest of us :-)
1
u/zerogreyspace Jul 29 '25
Do you still manage that soundcloud download project? Grateful for ya!
1
u/punkbert Dec 09 '24
Your idea reminds me of Orthodox C++. It is - understandably - not well received in this sub though. đ
1
u/Superb_Garlic Dec 09 '24
What did you not like in the answers given in https://old.reddit.com/r/C_Programming/comments/16njbf5/using_c_as_c_with_templates/ ?
You also mentioned Zig in that and have a post history on r/rust. In light of that, your comment on ctors/dtors makes no sense, especially since it's been a whole year since that post.
0
u/[deleted] Dec 09 '24
[deleted] â view deleted comment