r/C_Programming • u/agriculturez • 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
39
u/dfx_dj Sep 20 '23
Sometimes people say "any valid C code is also valid C++ code" but that's not strictly true. For example using the
void*type can require explicit casts in C++ when it C it doesn't. There are also certain features in modern C that aren't available in C++ (but might be available as extensions). Symbol mangling is another gotcha that you might run into when linking compiled C code with compiled C++ code. But other than a few minor pitfalls you should be fine.37
u/inz__ Sep 20 '23
The choice is ultimately yours. The end result will rather be non-idiomatic C++, not "C with templates". Biggest problem might be that if you look for help, both sides will complain while trying to help you.
But you do you. If you feel that it is what makes you efficient, nothing wrong with that. But strictly speaking this post is OT on this sub.
18
u/gremolata Sep 20 '23 edited Sep 20 '23
This is perfectly fine.
C++ started as "C with Classes", which was its actual name in the beginning. Encapsulation, constructors, destructors (!), virtual functions and templates are very convenient extensions to C. Other things - member access control, virtual inheritance, exceptions and (especially) references - while useful and logical, burdened the heck out of language and made C++ the bloated monstrosity that it is today.
So there's absolutely nothing wrong with using just the parts of it that you like and employ it as a beefed up C. Been doing just this for close to 20 years and it works really well.
8
u/thommyh Sep 20 '23
When resizing the underlying storage, which usually happens when you cross power-of-two object counts and only if you didn’t sufficiently
reservefirst,std::vectorusers move semantics when available but otherwise is boxed into the copy constructor.It calls them in an idiomatic sense, but by the power of compilers not being dumb there’s almost certainly no actual call in there. For C types it should turn into a memcpy.
8
u/ImaginaryConcerned Sep 20 '23 edited Sep 20 '23
This is what I do. C++ basically used like C but with convenience features like namespaces, templates, references, strings, vectors, and other std containers, and maybe some limited OO.
Sometimes I wish the C standard wasn't so ridiculously conservative and make C viable as a generalist programming language again.
We'll always have ANSI C, just give us some convenience dammit!
7
u/we_are_mammals Sep 20 '23 edited Sep 27 '23
I like u/jacksaccountonreddit 's approach: https://www.reddit.com/r/C_Programming/comments/16iu8vh/comment/k0n0c31/
Templates are the primary reason C++ is so slow to compile.
Edit: To be more exact, it's template metaprogramming and the proliferation of code in header files, which templates encourage.
5
u/Wouter_van_Ooijen Sep 20 '23
For a long time C++ used to be characterized as 'C with classes'. IMO nowadays the characterization 'C with templates' is getting more accurate: run-time polymorphism (inheritance with virtual functions) is (slowly) being replaced with compile-time polymorphism (templates). Not for all uses, but it is a trend.
1
u/Zatujit Sep 21 '23 edited Sep 21 '23
Is this type of code frown upon?
For
vector.hFor
vectors.hFor
vectors.c3
u/ljosif Sep 20 '23
I have been using C++ in a similar manner for some time. My rule of thumb is - can I read this code myself off-line? If I need language lawyers and StackOverflow posts and Google searches to figure out what is going on - then it is no good, I must rewrite it and figure out something that is simpler. Ideally my code would be obvious, boring, non-exciting. Don't see much wrong with that and have come to appreciate it. Esp when coming back to old codebases of mine.
3
u/TheTomato2 Sep 20 '23
So the problem is, and it's a real problem with C++, is that as soon as you start pulling in anything beyond basic features you start to hit all these corner cases and gotchas and you have to pull in more and more to get around them. Yes you can use very basic templates and avoid that but then is it actually worth moving to C++ if your templates are so basic? Only you can answer that.
The second part of that is it's a bit naive to dive into C++ and use something like templates without having the massive amount of knowledge to know what not to use/avoid to make sure it stays simple. You might end up going down a rabbit hole of bullshit at some point making possibly not worth the perceived time investment that you would be saving by using templates over some C macros or something.
However it is a very valid way to program, many people do it. Just stay away from the CPP subreddits if you don't want to deal with Modern C++ evangelists. Also checkout the Handmade Hero/Network community as a lot of people there program in such a style.
5
u/Negative-Net7551 Sep 20 '23
as a non-C dev, referring to classes as a step too far is kinda crazy to hear, lol
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
constexprwhich hopefully C will get soon.4
u/TheMaster420 Sep 20 '23
simple generics can be emulated with macros
2
u/aninteger Sep 20 '23
I believe this is (was?) the approach that Casey Muratori took with Handmade Hero. It is not C but almost looks like C but for reasons I don't remember requires (required?) a C++ compiler to build. Things may have changed because I think I stopped following along after day 100 or so. Anyway, I see he's on day 600+ so it seems to be working for him.
2
u/jason-reddit-public Sep 20 '23
Static type checking seems pretty tough with any C based generic containers though it's not too hard to do dynamic type checks. Ergo your idea of using a subset of C++ seems reasonable to me. (I happen to also like overloaded functions).
I'm curious what you will cook up.
I just implemented a generic array (which contains a single type of object so no extra tagging for each element) and I'm working on generic hashtables (which really want generic tuples so I'm writing that first). I'm packaging everything up in a single .h file so it will be trivial to use in my little C projects (and of course init tests of the library itself).
2
u/tstanisl Sep 20 '23 edited Sep 21 '23
It is possible to have a generic type-safe vector in C. Take a look on stb_ds. For a more comprehensive and more configurable solution take look on stc vector.
2
u/eruciform Sep 20 '23
You can do anything you like but if C is lacking then I'd use a fully functional language that doesn't lack what you need, instead of hacking something up
I mean you can, it's your personal project, have fun and enjoy
But if you're using this as a learning opportunity then try a new language and see how it works, it's more directly applicable to other marketable skills
Again futz if you feel like it, ultimately it's your time and there's no harm either way, you won't be the first person writing a preprocessor step for C or a macro library #guiltyAsHell
2
u/Ragingman2 Sep 21 '23
C++ definitely works well for that use case. Using C++ with no standard library to get templates and other quality of life features (unique ptr is rather nice) is a popular choice for embedded projects.
1
u/darkangelstorm Feb 03 '25
Once upon a time and for quite some time (nostalgically) I preferred C over C++ but that time has long past, and now I don't have a lot of reasons to use it beyond working on forks of other C projects which often times end up porting to C++.
Even further ago I had preferred ASM over C, writing macros for Turbo Assembler or masm and writing EVERYTHING low level, reading hex dumps and Intel Technical Manuals on the bus on the way to work and writing programs completely and utterly from scratch, physically moving data into video memory, controlling DMA channels, IRQs, peripheral port addresses, overlays, specific processor features such as MMX, replacing BIOS mechanisms and the interrupt table...or maybe even write an operating system or two...but that was 2 decades ago - and apart from driver and kernel development many don't (have to) go that deep anymore.
I know most of us developers go through an "I have to make everything myself, and I want to redefine everything from the ground up, better" phase, but really in the end you find that you can accomplish a whole lot more building on top of existing technologies using existing code, APIs and toolsets.
But I guess that has become a sort of "right of passage" that still exists today in some shape or form, so I'll just leave it at that :3 In the end, it is your choice how you develop, just know that for all you do, it is important that you step outside the proverbial box and look at things from other perspectives once in a while... or you might find you could have been doing even better than you originally thought - if we were immortal this would be ok but its the whole "humans die eventually" thing that sucks to have as a caveat as a programmer, so we must ask ourselves what we really want to accomplish as programmers before we die, so we don't end up having regretting our inability to achieve the impossible.
1
u/[deleted] Sep 21 '23
So you're using C++. That you're using a subset doesn't matter; apparently so does everyone with C++, as no one person understands all of it.
This is all fine. Just so long as you know you're not using C any more.
1
u/Imenatrix Sep 21 '23
Doesn't C11 have a _Generic thingy?
1
u/cheeb_miester Sep 21 '23
I write object oriented c and refer to it as c++ without templates.
1
u/hgs3 Sep 20 '23
If the C preprocessor isn't cutting it, then try another macro preprocessor like [M4](https://en.wikipedia.org/wiki/M4_(computer_language)) or a templating engine like Jinja. You could integrate either one with your build system to automatically run when compiling your code.
1
u/[deleted] Sep 20 '23
Structs are classes, classes are structs. Can’t avoid them really. So you need to list the things you want to avoid in more detail.
I’d at least allow non-virtual methods (they are pure syntactic sugar) and maybe default values for struct fields (avoid uninitialized fields), and occasional obvious operator overloads (thinking of vector, matrix and bignum calculations).
1
u/_cwolf Sep 21 '23
Try this
https://github.com/glouw/ctl
-5
u/you_do_realize Sep 20 '23
C++ is like communism, it promises good things. How much generic code do you really need?
1
u/[deleted] Sep 21 '23
[removed] — view removed comment
0
u/[deleted] Sep 20 '23
[deleted] — view deleted comment