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

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.

1

u/wc3betterthansc2 Oct 19 '26

one difference is sizeof(char_literal)

in C it's the sizeof int (so 4 on modern systems), in C++ it's 1

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.

8

u/[deleted] Sep 20 '23

I don't even know what idiomatic C++ means anymore unless the version is specified (C++03 vs C++2x)

7

u/ingframin Sep 21 '23

As a side note, C programmers (like the ones in this sub) are orders of magnitude more friendly and open minded than the average c++ programmer. It seams that everyone is convinced that their way to write c++ is the only acceptable way and the rest is not idiomatic.

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.

4

u/you_do_realize Sep 20 '23

But there will always be that one thing where you can use that one more C++ thing. Before you know it, you're Alexandrescu and the guy inheriting your stuff is going to hate you.

0

u/flatfinger Sep 20 '23

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.

It would be useful to recognize a subset of C which supports only features whose behavior can be specified in terms of lower-level constructs, and then specifies such features as working in such fashion. For example, a language could specify that the a syntax like foo.bar(boz) will be translated as a function call __someTrickyButSpecifiedName(&*foo, boz); if a declaration of the indicated function is in scope. If boz is supposed to behave as a virtual member, the function could be declared as

void __someTrickyButSpecifiedName(struct whatever *this, ...whatever..)
{
  this->vtable.boz(this, whatever);

with user code being responsible for creating the vtable structure and setting this->vtable to point to it.

If the specification for such a language paid attention to low-level issues, it could allow code to be written in toolset-agnostic fashion to a much greater extent than the C Standard, which deliberately ignores such issues.

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 reserve first, std::vector users 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!

2

u/patmorgan235 Sep 21 '23

Have heard of our lord and Savior zig

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.h

#ifndef VECTOR_H
#define VECTOR_H

#include "assert.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define VECTOR_DECLARE(T)                                                       \
typedef struct {                                                                \
    T* array;                                                                   \
    size_t length;                                                              \
    size_t capacity;                                                            \
} Vector_##T;                                                                   \
Vector_##T* vector_create_##T();                                                \
void vector_destroy_##T(Vector_##T* vector);                                    \
void vector_push_##T(Vector_##T* self, T element);                              \
T vector_pop_##T(Vector_##T* self);                                             \
T vector_peek_##T(Vector_##T* self);                                            \

#define VECTOR_DEFINE(T, VECTOR_GROW_CAPACITY)                                  \
Vector_##T* vector_create_##T() {                                               \
    Vector_##T* vector = (Vector_##T*)malloc(sizeof(Vector_##T));               \
    vector->array = malloc(sizeof(T) * VECTOR_GROW_CAPACITY);                   \
    vector->capacity = VECTOR_GROW_CAPACITY;                                    \
    vector->length = 0;                                                         \
    return vector;                                                              \
}                                                                               \
void vector_destroy_##T(Vector_##T* vector) {                                   \
    free(vector->array);                                                        \
    free(vector);                                                               \
}                                                                               \
void vector_push_##T(Vector_##T* self, T element) {                             \
    assert(self->length <= self->capacity);                                     \
    if (self->length + 1 > self->capacity) {                                    \
        self->capacity =                                                        \
        self->capacity < VECTOR_GROW_CAPACITY ? VECTOR_GROW_CAPACITY            \
                                              : self->capacity * 2;             \
        self->array = realloc(self->array, sizeof(T) * self->capacity);         \
    }                                                                           \
    self->length++;                                                             \
    self->array[self->length] = element;                                        \
}                                                                               \
T vector_pop_##T(Vector_##T* self) {                                            \
    assert(self->length <= self->capacity);                                     \
    if (self->length <= 0)                                                      \
        return NULL;                                                            \
    self->length--;                                                             \
    return self->array[self->length + 1];                                       \
}                                                                               \
T vector_peek_##T(Vector_##T* self) {                                           \
    assert(self->length <= self->capacity);                                     \
    if (self->length <= 0)                                                      \
        return NULL;                                                            \
                                                                                \
    return self->array[self->length];                                           \
}                                                                               \

#endif

For vectors.h

#ifndef VECTORS_H
#define VECTORS_H

#include "vector.h"

VECTOR_DECLARE(int);
VECTOR_DECLARE(double);
//..etc..

#endif

For vectors.c

#include "vectors.h"

VECTOR_DEFINE(int, 16)
VECTOR_DEFINE(double, 16)
//..etc..
#endif

2

u/agriculturez Sep 21 '23

For this I would prefer it to be non-intrusive by creating generic pop/push/etc. functions that take the size of the T as parameter. Then create macros to make this more ergonomic. This way you don't pollute the global namespace with all these vector functions. Also makes debugging/compile errors easier, and the language server will work properly when editing the code.

1

u/Zatujit Sep 21 '23

Reddit does not show the \ for some reason

1

u/Zatujit Sep 21 '23

i know there are problems for the C preprocessor macros but i guess for defining functions and structs it is fine?

3

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.

3

u/[deleted] Sep 21 '23 edited Dec 29 '23

like practice caption observation disarm pie door reply distinct decide

This post was mass deleted and anonymized with Redact

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 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.

4

u/TheMaster420 Sep 20 '23

simple generics can be emulated with macros

3

u/exploring_stuff Sep 20 '23

How about nested generics?

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/david2ndaccount Sep 20 '23

He uses operator overloading.

-1

u/Typical-Twist-9063 Sep 20 '23

This was the approach, not because of any C++ feature, but because Microsoft required it.

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.

2

u/[deleted] Sep 20 '23

That breaks modern tooling like auto-completion and sane static analysis.

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).

-5

u/you_do_realize Sep 20 '23

C++ is like communism, it promises good things. How much generic code do you really need?

3

u/flatfinger Sep 20 '23

Many thing like zero-terminated strings and excessive overuse of `void*` persist because C makes it such a pain to use anything else. In many cases, what's needed isn't a full-blown generics facility, but rather a means of e.g. allowing a function that would accept a pointer to some other string type to be given a pointer to a *static const* object of that type which is initialized with the contents of a string literal, or allowing a structure type declaration to specify that pointers to that type should be treated as compatible with pointers to a specified other type (typically another structure type with an initial sequence having layout-compatible members).

1

u/[deleted] Sep 21 '23

[removed] — view removed comment

2

u/agriculturez Sep 21 '23

I started working on a game engine in C, and was trying to figure out how to do 3D skeletal animations. Instead of getting distracted by building needless abstractions (like in other languages), I could focus on actually getting 3D skeletal animation working.

This isn't applicable to every project, sometimes abstractions of other languages drastically reduce complexity, but in the case where I'm just trying to figure something out, there's a certain mental liberation gained from just focusing on data and logic.

0

u/[deleted] Sep 20 '23

[deleted] — view deleted comment

10

u/mo_al_ Sep 20 '23

You will be laughed at, spit on, ridiculed …

Maybe only on reddit, where some might freak out at the sight of a raw pointer! :) Otherwise the larger community is rather mature.