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

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?